我想在文本框为空时禁用警报按钮。
我把按钮放在表视图单元格中。因此,当您单击该按钮时,将弹出警告框。
我的代码如下。
func cellTapped(cell: DeviceListTableCell) {
self.showAlertForRow(row: tableView.indexPath(for: cell)!.row)
}
func showAlertForRow(row: Int) {
let alert = UIAlertController(
title: "Enter Password !!!!!",
message: "",
preferredStyle: .alert)
alert.addTextField { (textField) in
}
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
let pwd = alert.textFields?[0]
self.password = pwd?.text
debugPrint(self.password)
debugPrint("Press OK")
DispatchQueue.main.async(execute: {
if(self.password == ""){
debugPrint("Null Password!")
}else{
debugPrint("Not Null Password!")
}
})
}
alert.addAction(okAction)
// Present the controller
DispatchQueue.main.async(execute: {
self.present(alert, animated: true, completion: nil)
})
}
和
protocol ButtonCellDelegate {
func cellTapped(cell: DeviceListTableCell)}
有人可以帮我解决如何禁用/启用警报按钮的问题吗?
答案 0 :(得分:0)
观察UITextFieldTextDidChange
通知,以便在更改文本时收到通知,然后启用和禁用okAction
// Create an alert controller
let alertController = UIAlertController(title: "Alert", message: "Please enter text", preferredStyle: .alert)
// Create an OK Button
let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
// Print "OK Tapped" to the screen when the user taps OK
print("OK Tapped")
}
// Add the OK Button to the Alert Controller
alertController.addAction(okAction)
// Add a text field to the alert controller
alertController.addTextField { (textField) in
// Observe the UITextFieldTextDidChange notification to be notified in the below block when text is changed
NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main, using:
{_ in
// Being in this block means that something fired the UITextFieldTextDidChange notification.
// Access the textField object from alertController.addTextField(configurationHandler:) above and get the character count of its non whitespace characters
let textCount = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines).count ?? 0
let textIsNotEmpty = textCount > 0
// If the text contains non whitespace characters, enable the OK Button
okAction.isEnabled = textIsNotEmpty
})
}