I'm trying to disable the continue button if there is nothing in the text field. Here's my code...
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
}
}
since you've already made your class a UITextFieldDelegate ad this function
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
}
also update your viewDidLoad function
override func viewDidLoad() {
super.viewDidLoad()
nounTextField.delegate = self
if nounTextField.text.isEmpty{
continueButton.userInteractionEnabled = false
}
}
Swift 5 version
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With