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

时间:2015-12-10 16:13:15

标签: 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
} 
}

6 个答案:

答案 0 :(得分:5)

因为您已经将您的课程设为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 
    }
}

答案 1 :(得分:3)

Swift 4版本

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{
        //make isUserInteractionEnabled = true 
    } else {
        //make isUserInteractionEnabled = false 
    }

    return true
}

答案 2 :(得分:1)

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

我测试了很多情况,包括“剪切/粘贴”操作,看来还可以。如果在进一步测试中发现问题,我会纠正我的答案。

答案 3 :(得分:0)

if nounTextField.text == ""{
  continueButton.enabled = false
}

答案 4 :(得分:0)

试试这个:

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

答案 5 :(得分:0)

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

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

    return true
}