UITextField限制输入文字的个数

2021-10-29 14:12:43 浏览数 (1)

代码如下:

static constNSInteger Max_Character_Num =4;

代码语言:javascript复制
    - (IBAction)onTextFieldEditingChanged:(id)sender  
    {  
        NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];  
        if ([lang isEqualToString:@"zh-Hans"]) {  
            UITextRange *selectedRange = [self.tagNameTextField markedTextRange];  
            UITextPosition *position = [self.tagNameTextField positionFromPosition:selectedRange.start offset:0];  
            if (!position) {  
                if (self.tagNameTextField.text.length > Max_Character_Num) {  
                    self.tagNameTextField.text = [self.tagNameTextField.text substringFrom:0 to:Max_Character_Num];  
                }  
            }  
        }else{  
            if (self.tagNameTextField.text.length > Max_Character_Num) {  
                self.tagNameTextField.text = [self.tagNameTextField.text substringFrom:0 to:Max_Character_Num];  
            }  
        }  
    }  

0 人点赞