美文网首页
iOS输入框限制输入内容和输入长度

iOS输入框限制输入内容和输入长度

作者: 小巧书童 | 来源:发表于2021-11-04 10:57 被阅读0次

    限制输入框输入长度

    [TextFiled addTarget:self action:@selector(textfieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    [self.TextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    -(void)textFieldDidChange:(UITextField *)textField

    {

        NSUInteger maxLength =11;

        NSString*toBeString = textField.text;

        //获取高亮部分

        UITextRange*selectedRange = [textFieldmarkedTextRange];

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

        if(!position || !selectedRange)

        {

            if(toBeString.length> maxLength)

            {

                NSRangerangeIndex = [toBeStringrangeOfComposedCharacterSequenceAtIndex:maxLength];

                if(rangeIndex.length==1)

                {

                    textField.text= [toBeStringsubstringToIndex:maxLength];

                }

                else

                {

                    NSRangerangeRange = [toBeStringrangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];

                    textField.text= [toBeStringsubstringWithRange:rangeRange];

                }

            }

        }

    }

    限制输入框输入内容

    //数字

    #define NUM @"0123456789"

    //字母

    #define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

    //数字和字母

    #define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

    #pragma mark -- UITextFieldDelegate

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

        //数字和字母

        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];

        //数字

        //NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUM] invertedSet];

        //字母

        //NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];

        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

        return[stringisEqualToString:filtered];

    }

    相关文章

      网友评论

          本文标题:iOS输入框限制输入内容和输入长度

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