@interface UITextField (LimitTextLength)
/**
* 截断至某个长度
*
* @param index :长度
* @return 返回是否成功截断
*/
- (BOOL)treateTextFieldToIndex:(int)index;
@end
@implementation UITextField (LimitTextLength)
- (BOOL)treateTextFieldToIndex:(int)index {
NSString *toBeString = self.text;
//获取高亮部分
UITextRange *selectedRange = [self markedTextRange];
UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position || !selectedRange) {
if (toBeString.length > index) {
NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:index];
if (rangeIndex.length == 1) {
self.text = [toBeString substringToIndex:index];
} else {
NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, index)];
self.text = [toBeString substringWithRange:rangeRange];
}
return YES;
}
}
return NO;
}
@end
调用
[_nameTextField.textLabel addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
- (void)textFieldDidChange:(UITextField *)textField {
[textField treateTextFieldToIndex:11];
}