ios - 当用户从 UITextfield 清除文本时禁用按钮
问题描述
第一次加载视图时,我可以禁用该按钮。即使textfield
是空的。但是在发送消息后,当我输入并从中删除文本时textfield
它不起作用。button
交互仍然有效,用户可以发送不想要的空消息。当用户键入并删除文本时,我仍想禁用该按钮,以防他们改变主意。这是我的代码。
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var sendButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
if textField.text!.isEmpty {
sendButton.isUserInteractionEnabled = false
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let inputText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if !inputText.isEmpty {
sendButton.isUserInteractionEnabled = true
} else {
sendButton.isUserInteractionEnabled = false
}
return true
}
解决方案
Add listener for your text field, for which you want to disable your action button like this in your viewDidLoad method
textField.addTarget(self, action: #selector(actionTextFieldIsEditingChanged), for: UIControlEvents.editingChanged)
And upon call this method, check for text field is empty or not:
@objc func actionTextFieldIsEditingChanged(sender: UITextField) {
if sender.text.isEmpty {
sendButton.isUserInteractionEnabled = false
} else {
sendButton.isUserInteractionEnabled = true
}
}
推荐阅读
- kubernetes - 具有动态规则的 Prometheus 服务器
- angular - 带有 mat-checkbox 的 Angular 复选框列表
- python - 如何限制值提供的日期和时间
- firebase - 仅允许空文档的 Firestore 安全规则
- django - Django DEBUG = 真正的 xlsx 文件不起作用
- android - 如何从我的应用程序访问 google drive api
- reactjs - 组件的可选属性?
- android - React Native:同时使用 firebase 和 sqlite 有意义吗?
- r - 如何在 R 中对参差不齐的数据框使用函数
- python - 在 python ffmpeg 上剪切、连接和转换