如果 TextField 为空,则禁用按钮

Disable Button if TextField is empty

如果 TextField 为空,我需要禁用按钮。否则它会使我的应用程序崩溃

(Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value).

我知道,这里人们写了很多次。但我尝试了 Whosebug 中的许多示例,例如:

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 方法来启用按钮。

class ViewController: UIViewController { 

   override func viewDidLoad() {
    super.viewDidLoad()

       myTextField.delegate = self
   }

}

实现这个委托方法...

extension ViewController: UITextFieldDelegate { 


  func textFieldDidEndEditing(_ textField: UITextField) {

    if let text = textField.text, text.isEmpty {
        MyButton.isUserInteractionEnabled = false
        MyButton.isEnabled = false
        MyButton.alpha = 0.5
    } else {
       MyButton.isUserInteractionEnabled = true
        MyButton.isEnabled = true
        MyButton.alpha = 1
   }

  }

}

您也可以在 viewDidLoad 方法中禁用按钮。

if let text = MyTextField.text, text.isEmpty {
    MyButton.isUserInteractionEnabled = false
    MyButton.isEnabled = false
    MyButton.alpha = 0.5
} 

编辑

您还可以在用户在文本字段中键入时启用和禁用按钮。

extension ViewController: UITextFieldDelegate {  

  func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)

    if text.isEmpty{

        MyButton.isUserInteractionEnabled = false
        MyButton.isEnabled = false
        MyButton.alpha = 0.5

    } else {

        MyButton.isUserInteractionEnabled = true
        MyButton.isEnabled = true
        MyButton.alpha = 1
   }

    return true
  }
}
@IBAction func acceptButton(_ sender: Any) {
  if (MyTextField.text?.isEmpty)! {
    print("i am not doing anything")
   }
  else{
      //perform the code
  }
 }

为此使用UITextFieldDelegate方法shouldChangeCharactersIn

首先像这样将 class 与 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
    }

第一组

override func viewDidLoad()
{
    super.viewDidLoad()
    btn.isEnabled = false
}

然后在文本字段委托方法中

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    print(textField.text?.count ?? "default")
    if textField == MyTextField
    {
    if MyTextField.text?.count == 1 && string == ""
            {
                MyButton.isEnabled = false
            }
            else
            {
                MyButton.isEnabled = true
            }
    }
    return true
}

我没有看到完整的答案,所以这里是:

  1. iOS 有一个严格的约定,变量名和函数名应该以小写字母开头。只有 类 和类型应该以大写字母开头。因此,在下面的代码中,我将 MyButton 更改为 myButton,将 MyTextField 更改为 myTextField
  2. 不要使用 isUserInteractionEnabledalpha。只需设置按钮的 isEnabled 标志,让 UIKit 决定如何绘制禁用的按钮。这样您就可以遵循正常的 HIG 约定来显示禁用的按钮。
  3. 将代码添加到您的 viewWillAppear(_:) 函数以在文本字段为空时禁用该按钮。

像这样:

override func viewWillAppear(_ animated: Bool) {
    myButton.isEnabled = (myTextField.text?.count ?? 0) > 0
}
  1. 使您的视图控制器符合 UITextFieldDelegate 协议。然后按住 control 从文本字段拖动到视图控制器以连接委托 link.

  2. 向您的视图控制器添加一个 textField(_:shouldChangeCharactersIn:replacementString:) 函数以在文本字段为空时禁用该按钮。注意这个函数要判断替换完成后文本字段是否为空,所以需要计算字符串被替换后字段文本的长度。您可以在视图控制器的扩展中添加 UITextFieldDelegate 函数,这样可以很好地将它们分开。

像这样:

extension ViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, 
      shouldChangeCharactersIn range: NSRange, 
      replacementString string: String) -> Bool {
        //Make sure this method is being called
        guard textField == myTextField else { return true }
        let newLength = (textField.text?.count ?? 0) - range.length + string.count
        myButton.isEnabled = newLength > 0
        return true
    }
}