可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am trying to check when a text field changes, equivalent too the function used for textView - textViewDidChange so far I have done this:
func textFieldDidBeginEditing(textField: UITextField) { if self.status.text == "" && self.username.text == "" { self.topRightButton.enabled = false } else { self.topRightButton.enabled = true } }
Which kind of works, but the topRightButton is enabled as soon as the text field is pressed on, I want it to be enabled only when text is actually typed in?
回答1:
SWIFT
textField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
Then you can just call your function!
func textFieldDidChange(textField: UITextField) { //your code }
SWIFT 2.2
textField.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)
and
func textFieldDidChange(textField: UITextField) { //your code }
SWIFT 3
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
and
func textFieldDidChange(_ textField: UITextField) { }
Swift 4
@objc func textFieldDidChange(_ textField: UITextField) { }
OBJECTIVE-C
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
and textFieldDidChange method is
-(void)textFieldDidChange :(UITextField *) textField{ //your code }
回答2:
You can make this connection in interface builder.
In your storyboard, click the assistant editor at the top of the screen (two circles in the middle). 
Ctrl + Click on the textfield in interface builder.
Drag from EditingChanged to inside your view controller class in the assistant view. 
Name your function ("textDidChange" for example) and click connect. 
回答3:
Swift 3.0
textField.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged)
and handle method:
func textFieldDidChange(textField: UITextField) { }
Swift 4.0
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: UIControlEvents.editingChanged)
and handle method:
@objc func textFieldDidChange(_ textField: UITextField) { }
回答4:
Swift 3
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(sender:)), for: UIControlEvents.editingChanged)
回答5:
The way I've handled it so far : in UITextViewDelegate
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // text hasn't changed yet, you have to compute the text AFTER the edit yourself let updatedString = (textField.text as NSString?)?.stringByReplacingCharactersInRange(range, withString: string) // do whatever you need with this updated string (your code) // always return true so that changes propagate return true }
回答6:
Swift 3.0.1+ (Some of the other swift 3.0 answers are not up to date)
textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: