【问题标题】:How to disable a button if a text field is empty?如果文本字段为空,如何禁用按钮?
【发布时间】:2015-12-10 16:13:14
【问题描述】:

如果文本字段中没有任何内容,我正在尝试禁用继续按钮。 这是我的代码...

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var nounTextField: UITextField!
@IBOutlet weak var `continue`: UIButton!

var noun = String()

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func continueButton(sender: AnyObject) {
    noun = nounTextField.text!
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let nvc = segue.destinationViewController as! ViewController2
    nvc.noun2 = noun
} 
}

【问题讨论】:

  • 无关的,总是在viewDidLoad中调用super

标签: ios swift


【解决方案1】:

因为你已经让你的类成为一个 UITextFieldDelegate 和这个函数

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

    let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)

    if !text.isEmpty{
        continueButton.userInteractionEnabled = true 
    } else {
        continueButton.userInteractionEnabled = false 
    } 
    return true
}

同时更新您的 viewDidLoad 函数

override func viewDidLoad() {
    super.viewDidLoad()

    nounTextField.delegate = self
    if nounTextField.text.isEmpty{
        continueButton.userInteractionEnabled = false 
    }
}

【讨论】:

  • 谢谢。我在 continue.userInteractionEnabled 处不断收到错误消息。它说一行上的连续语句必须用 ; 分隔
  • 表示一行中连续的语句必须用 ; 分隔
  • 我注意到在你的代码中 continue 变量在它周围有单引号'继续'。我不认为斯威夫特喜欢那样。可能想删除单引号。
  • 三个观察:与其修改userInteractionEnabled,不如切换enabled。其次,UITextFieldtext 属性是可选的,因此当您将其转换为NSString 时必须将其解包。第三,您可以将 if-else 子句简化为 continueButton.enabled = !text.isEmpty()
  • 仅供未来读者参考:以编程方式设置文本字段的文本时,不会调用此委托方法。如果您有一个手动/不使用键盘设置文本的代码路径,则需要单独处理
【解决方案2】:

Swift 5 版本

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

    guard let oldText = textField.text else {
        return false
    }
    
    let newText = (oldText as NSString).replacingCharacters(in: range, with: string)
    continueButton.isEnabled = !newText.isEmpty
    return true
}

【讨论】:

  • let newText = (oldText as NSString).replacingCharacters(in: range, with: string) 可以或者写成let newText = oldText.replacingCharacters(in: Range(range, in: oldText)!, with: string),避免强制转换;感谢 Foundation 扩展 String 以公开由 NSString 定义的方法。
【解决方案3】:

@Steve 的回答是我认为的正确方法。我们可以通过更快的检查来进一步优化空检测:

continueButton.isEnabled = (!replacementString.isEmpty || range.length < (textField.text ?? "").count)

这可以作为 UITextField 扩展提供:

extension UITextField {
    func changeDoesNotLeadToEmptyString(replacingCharactersIn range: NSRange, with replacementString: String) -> Bool {
        return (!replacementString.isEmpty || range.length < (text ?? "").count)
    }
}

我测试了很多案例,包括剪切/粘贴操作,它似乎工作正常。如果我在进一步测试中发现问题,我会更正我的答案。

【讨论】:

    【解决方案4】:
    if nounTextField.text == ""{
      continueButton.enabled = false
    }
    

    【讨论】:

      【解决方案5】:

      试试这个:

      if nounTextField!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).isEmpty ||
                          nounTextField.text == nil{
      `continue`.enabled = false
      }
      

      【讨论】:

      • 这应该去哪里?
      • 首先,在 viewDidLoad 中将文本字段的委托设置为 self,因为您已经通过这样做继承了 UITextFieldDelegate:nounTextField.delegate = self,然后添加此 nounTextField.addTarget(self, action:" textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged) 将在文本字段值更改时为其提供一个目标,最后创建具有给定名称的函数,在本例中为 func textFieldDidChange(textField: UITextField){//insert代码在这里}
      【解决方案6】:

      如果文本字段中有一个“全部清除”按钮,您还应该实现以下方法。因为如果您使用“全部清除”按钮清除文本字段,则不会调用“shouldChangeCharactersInRange”方法。

      func textFieldShouldClear(_ textField: UITextField) -> Bool {
          yourbutton.isEnabled = false
      
          return true
      }
      

      【讨论】:

        猜你喜欢
        • 2020-06-03
        • 1970-01-01
        • 2016-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多