iOS中UITextField的字数限制

2023-10-29  本文已影响0人  ios_暗夜行者

 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChanged:)

              name:@"UITextFieldTextDidChangeNotification" object:self.textField];

#pragma mark - Notification Method

-(void)textFieldEditChanged:(NSNotification *)obj

{

    UITextField*textField = (UITextField*)obj.object;

    NSString*toBeString = textField.text;

    //获取高亮部分

    UITextRange*selectedRange = [textFieldmarkedTextRange];

    UITextPosition*position = [textFieldpositionFromPosition:selectedRange.startoffset:0];

    // 没有高亮选择的字,则对已输入的文字进行字数统计和限制

    if(!position)

    {

        if(toBeString.length>MAX_STARWORDS_LENGTH)

        {

            NSRangerangeIndex = [toBeStringrangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];

            if(rangeIndex.length==1)

            {

                textField.text= [toBeStringsubstringToIndex:MAX_STARWORDS_LENGTH];

            }

            else

            {

                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];

                textField.text= [toBeStringsubstringWithRange:rangeRange];

            }

        }

    }

}

上一篇下一篇

猜你喜欢

热点阅读