我试图快速制作一个文本字段,该文本字段将允许启用按钮,但前提是该文本字段包含整数。我怎样才能做到这一点?
UITextFieldDelegate
IBOutlet
viewDidLoad
isEnabled
false
self
textField.delegate
textField:shouldChangeCharactersInRange:replacementString:
Int
Int(text)
这是代码:
class ViewController : UIViewController, UITextFieldDelegate { @IBOutlet weak var textField: UITextField! @IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() button.isEnabled = false textField.delegate = self textField.keyboardType = .numberPad } 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 Int(text) != nil { // Text field converted to an Int button.isEnabled = true } else { // Text field is not an Int button.isEnabled = false } // Return true so the text field will be changed return true } }