项目需要输入框的文字最多为4个,为了实现这个功能,在网上把资料翻遍了,没有一个能用的。后来不得不自己实现,折腾了好久,终于搞定了。小技巧分享给大家。
代码如下:
static constNSInteger Max_Character_Num =4;
- (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]; } } }
时间: 2024-10-17 10:50:39