1.直接監(jiān)聽 - 推薦
#pragma mark - 直接添加監(jiān)聽方法
-(void)addTargetMethod{
? ? [self.textField1 addTarget:self action:@selector(textField1TextChange:) forControlEvents:UIControlEventEditingChanged];
}
-(void)textField1TextChange:(UITextField *)textField{
? ? NSLog(@"textField1 - 輸入框內(nèi)容改變,當(dāng)前內(nèi)容為: %@",textField.text);
}
2.NSNotificationCenter 添加監(jiān)聽方法
#pragma mark - NSNotificationCenter 添加監(jiān)聽方法
-(void)addNSNotificationCenter{
? ? [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textField2TextChange:) name:UITextFieldTextDidChangeNotification object:self.textField2];
}
-(void)textField2TextChange:(NSNotification *)noti{
? ? UITextField *currentTextField = (UITextField *)noti.object;
? ? NSLog(@"textField2 - 輸入框內(nèi)容改變,當(dāng)前內(nèi)容為: %@",currentTextField.text);
}
-(void)dealloc{
? ? [[NSNotificationCenter defaultCenter] removeObserver:self];
}
3.KVO : 注意這種方法不會(huì)直接監(jiān)聽鍵盤輸入而是監(jiān)聽 textField.text 的改變,代碼設(shè)置才會(huì)有效
-(void)addKVO{
? ? [self.textField3 addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
? ? self.textField3.text = @"123";
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
? ? if ([keyPath isEqualToString:@"text"] && object == self.textField3) {
? ? ? ? NSLog(@"textField3 - 輸入框內(nèi)容改變,當(dāng)前內(nèi)容為: %@",self.textField3.text);
? ? }else{
? ? ? ? [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
? ? }
}
-(void)dealloc{
? ? [self.textField3 removeObserver:self forKeyPath:@"text" context:nil];
}
4.代理 可以判斷接下來是否允許繼續(xù)輸入
#pragma mark - 代理-(void)addDelegate{
? ? //實(shí)現(xiàn) UITextFieldDelegate 協(xié)議? ? self.textField4.delegate = self;
}
#pragma mark? UITextFieldDelegate- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
? ? return YES;
}// return NO to disallow editing.
- (void)textFieldDidBeginEditing:(UITextField *)textField{
? ? NSLog(@"textField4 - 開始編輯");
}// became first responder
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
? ? return YES;
}// return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
- (void)textFieldDidEndEditing:(UITextField *)textField{
? ? NSLog(@"textField4 - 結(jié)束編輯");
}// may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason NS_AVAILABLE_IOS(10_0){
}// if implemented, called in place of textFieldDidEndEditing:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
? ? NSLog(@"textField4 - 正在編輯, 當(dāng)前輸入框內(nèi)容為: %@",textField.text);
? ? return YES;
}// return NO to not change text