完美解决UITextField中文输入长度限制问题.
程序员文章站
2022-04-05 18:33:41
...
因为中文输入有选择的问题 所以
经过测试之后 下面的代码完美 解决 这是oc的代码 swfit同理.
@property (assign, nonatomic) NSInteger checkLength;
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
[super drawRect:rect];
self.delegate = self;
self.checkLength = 16;//默认长度限制
[self setKeyboardType:UIKeyboardTypeDefault];
[self addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
- (void)textFieldDidChange:(UITextField *)textField{
NSMutableString *text = [textField.text mutableCopy];
NSString * string = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"%@", string);
if (string.length > self.checkLength) {
textField.text = [textField.text substringToIndex:self.checkLength];
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (string.length == 0) {
//<- 删除
return true;
}
NSMutableString *text = [textField.text mutableCopy];
NSString * string1 = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
if (string1.length < self.checkLength) {
return true;
}else{
return false;
}
}