如果文本字段为空,如何禁用按钮?

Joh*_*hnd 2 ios swift

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

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
} 
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 6

既然你已经为你的班级做了一个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
}
Run Code Online (Sandbox Code Playgroud)

还会更新您的viewDidLoad函数

override func viewDidLoad() {
    super.viewDidLoad()

    nounTextField.delegate = self
    if nounTextField.text.isEmpty{
        continueButton.userInteractionEnabled = false 
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 三个观察结果:我只是切换"启用",而不是修改`userInteractionEnabled`.其次,`UITextField`的`text`属性是可选的,所以当你把它转换为`NSString`时你必须打开它.第三,你可以将`if`-`else`子句简化为`continueButton.enabled =!text.isEmpty()`. (3认同)

Mah*_*dra 5

斯威夫特 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
}
Run Code Online (Sandbox Code Playgroud)