美文网首页已解决
UITextfeild输入截取

UITextfeild输入截取

作者: 虫yu | 来源:发表于2020-05-20 12:02 被阅读0次
// 通过通知\点击事件\xib连线,关联上EditChanged
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) 
          name:@"UITextFieldTextDidChangeNotification" object:myTextField];


-(void)textFieldEditChanged:(NSNotification *)obj {
  UITextField *textField = (UITextField *)obj.object;
    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];
            }
        }
    }
}

转自:

iOS中UITextField的字数限制

相关文章

网友评论

    本文标题:UITextfeild输入截取

    本文链接:https://www.haomeiwen.com/subject/vemgohtx.html