UItextField 文字變化時的監聽設定
阿新 • • 發佈:2019-01-31
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
NSString * currentString = [textField.textstringByReplacingCharactersInRange:range withString:string]; //得到輸入框的內容
if ([currentString length
{
//只顯示25個字元
textField.text = [currentString substringToIndex:25];
// 這個地方可以設定提醒使用者輸入字元超過最大長度
returnNO; // 此時不能改變輸入框的值
}
returnYES; // 能改變輸入框的值
}
這種方法發現有一個弊端,如果不是鍵盤輸入,而是根據鍵盤聯想直接更改textField的值,此方法不呼叫
此時,設定為textField新增事件
[_textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
//這種方法可以隨時監聽textField的字元變化
-(void)textChange:(UITextField *)textField{
// 輸入你想要的操作
}