美文网首页闻道技能(iOS-设计模式)iOS Developer
UITextField 限制字数的正确姿势

UITextField 限制字数的正确姿势

作者: iLees | 来源:发表于2017-06-02 15:36 被阅读78次
    @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];
    }
    

    相关文章

      网友评论

        本文标题:UITextField 限制字数的正确姿势

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