问题描述
我想添加功能,例如,如果 textfield
中没有任何字母并按下确认按钮,则 textfield
打印 "you must need to write folder name"
,并在显示打印时停止操作。我在谷歌找到了一些例子,但我不知道如何调整我的代码。
func folderAdDalert() {
let alert = UIAlertController(title: "Folder name",message: nil,preferredStyle: .alert)
alert.addTextField {(folderAddTF) in folderAddTF.placeholder = "Please add folder name"
print("+ clicked." )
}
let action = UIAlertAction(title: "Confirm",style: .default){ (_) in
guard let folder = alert.textFields?.first?.text else { return }
print("folderName: \(folder)")
self.folderNames.append(folder)
self.collectionView.reloadData()
}
let cancel = UIAlertAction(title: "Cancel",style: UIAlertAction.Style.default,handler: nil)
alert.addAction(action)
alert.addAction(cancel)
present(alert,animated: true,completion: nil)
}
}
解决方法
您的方式是正确的,但是在这里您需要检查文本字段是否为空,在用户按下确认按钮时进行验证
let action = UIAlertAction(title: "Confirm",style: .default){ (_) in
guard let folder = alert.textFields?.first?.text,!folder.isEmpty else {
self.present(alert,animated: true,completion: nil)
if let getPlaceholder = alert.textFields?.first,let placeHolderText = getPlaceholder.placeholder{
getPlaceholder.attributedPlaceholder = NSAttributedString(string: placeHolderText,attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
}
return }
print("folderName: \(folder)")
}