UITextField限制输入长度

首先,汉字的输入时的联想词在输入到TextFiled时,并不会走

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;

这导致了在这里进行长度限制的代码都会失效.此路不通.

 

因此我们可以用注册UITextFieldTextDidChangeNotification通知来监测TextField的文字的变化:

1、注册通知

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
          name:@"UITextFieldTextDidChangeNotification" object:myTextField];

 

2、实现 textFiledEditChanged: 方法

- (void) textFiledEditChanged:(NSNotification *)notification{
     
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBeString = textField.text;
 
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
 
    // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
    if (!position || !selectedRange) {
        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];
            }
        }
    }
}

至此,可以完美控制输入字符长度

posted @ 2018-09-23 14:58  Mr.pengge  阅读(379)  评论(0编辑  收藏  举报