UITextField字数限制

感谢http://www.jianshu.com/p/2d1c06f2dfa4

定义一个宏, 根据设计师要求确定限制多少字符

#define MAX_STARWORDS_LENGTH 5

添加监听事件

[_textField addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];

实现事件

- (void)textFieldDidChange{

NSString *toBeString = _textField.text;

//获取高亮部分
UITextRange *selectedRange = [_textField markedTextRange];
UITextPosition *position = [_textField positionFromPosition:selectedRange.start offset:0];

// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position){
    
    if (toBeString.length > MAX_STARWORDS_LENGTH){
        
        NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
        if (rangeIndex.length == 1){
            
            _textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
        }
        else{
            
            NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
            _textField.text = [toBeString substringWithRange:rangeRange];
        }
    }
}
}

你可能感兴趣的:(UITextField字数限制)