首页 > 解决方案 > 如果 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 年。

标签: iosswiftuibuttonuitextfield

解决方案


为此使用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
    }

推荐阅读