【问题标题】:Button not enabling/disabling when textfield has integer in it当文本字段中有整数时,按钮不启用/禁用
【发布时间】:2016-08-12 00:43:58
【问题描述】:

一旦用户将整数值输入到标有“华氏度”的文本字段中,我将尝试激活“转换”按钮。在文本字段中输入整数后,我无法激活文本字段。请参阅下面的代码以供参考

override func viewDidLoad() {
    super.viewDidLoad()
    Fahrenheit.becomeFirstResponder()
    Convert.enabled = false
    Fahrenheit.delegate = self
    Fahrenheit.keyboardType = .DecimalPad

    if Int(Fahrenheit.text!) != nil{
        Convert.enabled = true
    }else{
        Convert.enabled = false

    }

【问题讨论】:

    标签: swift button uitextfield


    【解决方案1】:

    您可以从UITextFieldDelegate 协议实现textField(textField:shouldChangeCharactersInRange:replacementString:) 并检查textField 是否包含任何文本:

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
      let currentText = NSString(string: textField.text ?? "")
      let newText = currentText.stringByReplacingCharactersInRange(range, withString: string)
    
      convertButton.enabled = !newText.isEmpty
      return true
    }
    

    或者,如果您确定只要文本字段是第一响应者,用户就不会按下按钮,您也可以在textFieldDidEndEditing(textField:) 中进行上述检查:

    func textFieldDidEndEditing(textField: UITextField) {
      convertButton.enabled = textField.text?.isEmpty ?? false
    }
    

    您可以使用我创建的test project

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      • 2018-06-18
      相关资源
      最近更新 更多