清單來實現這一目標的方法之一:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var button: UIButton!
//Need to have the ViewController extend UITextFieldDelegate for using this feature
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Find out what the text field will be after adding the current edit
let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
if !text.isEmpty{//Checking if the input field is not empty
button.userInteractionEnabled = true //Enabling the button
} else {
button.userInteractionEnabled = false //Disabling the button
}
// Return true so the text field will be changed
return true
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Setting the Delegate for the TextField
textField.delegate = self
//Default checking and disabling of the Button
if textField.text.isEmpty{
button.userInteractionEnabled = false // Disabling the button
}
}
}
Reference Link for the above solution
我清楚地知道如何啓用/禁用按鈕('button.enabled = FALSE')。我也知道如何檢查一個文本字段是否爲空('if textFieldName ==「」{action}') - 不能做新行,但它會在新行。我的問題是我不知道如何製作,所以它一直在檢查。我不能使用循環,因爲這會凍結我的程序... – cross 2015-04-04 15:42:43
@cross在最後一個評論中,應該說'if textFieldName.text =='「'我也會推薦你設置一個委託。 – cromanelli 2015-04-04 15:46:45
@cromanelli你的權利,謝謝! – cross 2015-04-04 15:49:55