ios - 如果 TextField 为空,则禁用按钮
问题描述
如果 TextField 为空,我需要禁用按钮。否则它会使我的应用程序崩溃
(线程 1:致命错误:在展开可选值时意外发现 nil)。
我知道,这里人们写了很多次。但我尝试了 StackOverflow 中的许多示例,例如:
if (MyTextField.text?.isEmpty)! {
MyButton.isEnabled = false
MyButton.alpha = 0.5
}
上面的代码我确实放在了 viewDidLoad 中,但它没有用。如果我把按钮像:
@IBAction func acceptButton(_ sender: Any) {
if (MyTextField.text?.isEmpty)! {
MyButton.isEnabled = false
MyButton.alpha = 0.5
...
然后按钮总是禁用。即使我在 TextField 中输入了一些数字。
下面的代码也不起作用:
override func viewDidLoad() {
super.viewDidLoad()
MyTextField.addTarget(self, action: #selector(actionTextFieldIsEditingChanged), for: UIControlEvents.editingChanged)
...
}
...
@objc func actionTextFieldIsEditingChanged(sender: UITextField) {
if sender.MyTextField.isEmpty {
MyButton.isEnabled = false
MyButton.alpha = 0.5
} else {
MyButton.isEnabled = true
MyButton.alpha = 1.0
}
}
其他部分代码我不能使用,因为它是从 2014 年到 2015 年。
解决方案
为此使用UITextFieldDelegate
方法shouldChangeCharactersIn
。
首先UITextFieldDelegate
像这样绑定你的类
class ClassName: UIViewController, UITextFieldDelegate { ...
然后将此代码添加到您的viewDidLoad
myTextField?.delegate = self
MyButton?.isUserInteractionEnabled = false
MyButton?.alpha = 0.5
并实现这个委托方法
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if !text.isEmpty{
MyButton?.isUserInteractionEnabled = true
MyButton?.alpha = 1.0
} else {
MyButton?.isUserInteractionEnabled = false
MyButton?.alpha = 0.5
}
return true
}
推荐阅读
- java - 如何使用 JavaFX 在表中设置取决于区域设置的小数分隔符
- c++ - 奇怪的 C++ 数组访问
- c++ - 在内存映射中使用 reinterpret_cast 时处理未定义的行为
- dialogflow-es - 现在有没有办法以两种不同的语言在 Action 中获取请求?
- c - 如何编译自定义 PulseAudio 模块?
- java - 无法启动 .jar 文件
- android - Loop I/PhoneWindow: generateLayout isLightNavi false, Visibility: 0 I/DecorView: 它不支持 bigbang
- winapi - Printwindow 打印有空白区域
- gradle - 如何在 Gradle 项目中创建 Karaf shell 命令
- javascript - 如何在渲染返回中编写 if else 反应本机