【问题标题】:Disable Button if TextField is empty如果 TextField 为空,则禁用按钮
【发布时间】:2018-11-28 07:48:53
【问题描述】:

如果 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 方法,例如 textFieldShouldReturn。此方法将在按下返回按钮时调用。
  • @meaning-matters 谢谢你。更新
  • 另一种方法是在点击按钮时检查UITextField 是否为空,是否将按钮设置为不执行任何操作,是否不让它执行您的代码。跨度>

标签: ios swift uibutton uitextfield


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    当文本字段中有文本时,您需要实现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
      }
    }
    

    【讨论】:

    • 我建议写两个函数:enableButton(_ button: UIButton)disableButton(_ button: UIButton)
    • 谢谢。但后来我的按钮总是禁用
    • 不要否定!text.isEmpty,只需交换ifelse 块并删除!
    • 两者都一样,只是让我的按钮被禁用:(
    • 该代码应该可以工作,但是 (a) 它构建字符串只是为了测试它们的长度,并且它使用 NSString,这在 Swift 中是不鼓励的。我的答案中的解决方案在不构建一次性字符串的情况下进行相同的计算。
    【解决方案3】:

    第一组

    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
    }
    

    【讨论】:

      【解决方案4】:
      @IBAction func acceptButton(_ sender: Any) {
        if (MyTextField.text?.isEmpty)! {
          print("i am not doing anything")
         }
        else{
            //perform the code
        }
       }
      

      【讨论】:

      • 一些反馈:你不需要在 if 周围加上括号,你在 else 之前缺少一个花括号,你不应该强制展开,你不应该为 if 强制展开,这样更好使用文本字段委托方法
      【解决方案5】:

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

      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 协议。然后从文本字段控制拖动到视图控制器以连接委托链接。

      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
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多