zoukankan      html  css  js  c++  java
  • iOS textfield 限制输入字数长度

    iOS textfield限制输入的最大长度

     [self.textFiled addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    -(void)textFieldDidChange:(UITextField *)textField
    {
        CGFloat maxLength = 14;
        NSString *toBeString = textField.text;
        
        //获取高亮部分
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        if (!position || !selectedRange)
        {
            if (toBeString.length > maxLength)
            {
                NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
                if (rangeIndex.length == 1)
                {
                    textField.text = [toBeString substringToIndex:maxLength];
                }
                else
                {
                    NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                    textField.text = [toBeString substringWithRange:rangeRange];
                }
            }
        }
    }
    
  • 相关阅读:
    iOS故事板下使用代码跳转页面
    眼见不一定为实
    UITableView
    iOS 备忘录
    统计代码行数
    iOS - 图片合成
    UI 素材
    xcode中xib使用小技巧
    svn不能提交静态库解决方案
    在webSocket中获取shiro报错
  • 原文地址:https://www.cnblogs.com/qqcc1388/p/6404532.html
Copyright © 2011-2022 走看看