监听键盘 限制输入字数
[self.inputTextField addTarget:self action:@selector(textfieldDidChange:) forControlEvents:UIControlEventEditingChanged];
- (void)textfieldDidChange:(UITextField *)textField{
UITextRange *selectedRange = [textField markedTextRange];
NSString *newText = [textField textInRange:selectedRange];
if (!newText.length) {
if (self.inputTextField.text.length > 10) {
self.inputTextField.text = [self.inputTextField.text substringToIndex:10];
self.characterNumLab.text = @"10/10";
return;
}
self.inputTextField.text = textField.text;
NSInteger numCount = textField.text.length;
self.characterNumLab.text = [NSString stringWithFormat:@"%ld/10", (long)numCount];
}
}
网友评论