项目需求:设置UITextField的字数限制
解决办法:我在UITextField的分类里面直接添加了addTarget的方法,在这个方法中UIControlEventEditingChanged监听输入字符的长度
但是在分类里面直接写的话会崩溃
//限制输入字符长度(tag设置)
+ (UITextField *)textFieldWithContent:(NSString *)content SuperView:(UIView *)superView TextColor:(UIColor *)textColor Tag:(NSInteger)tag TextAlignment:(NSTextAlignment)textAlignment
{
UITextField *textField = [[UITextField alloc] init];
textField.text = content;
textField.textColor = textColor;
textField.tag = tag;
textField.textAlignment = textAlignment;
[textField addTarget:self action:@selector(textFiledDidChangeds:) forControlEvents:UIControlEventEditingChanged];
[superView addSubview:textField];
return textField;
}
崩溃原因:
unrecognized selector sent to instance
发送到实例的无法识别的选择器
也就是说分类里面的的Target找不到实例对象,所以需要把id的参数也传出去。
//限制输入字符长度(tag设置)
+ (UITextField *)textFieldWithContent:(NSString *)content SuperView:(UIView *)superView TextColor:(UIColor *)textColor Tag:(NSInteger)tag TextAlignment:(NSTextAlignment)textAlignment textField:(id)ids
{
UITextField *textField = [[UITextField alloc] init];
textField.text = content;
textField.textColor = textColor;
textField.tag = tag;
textField.textAlignment = textAlignment;
[textField addTarget:ids action:@selector(textFiledDidChangeds:) forControlEvents:UIControlEventEditingChanged];
[superView addSubview:textField];
return textField;
}
最后创建这个输入框
_phoneField = [UITextField textFieldWithContent:@"" SuperView:self TextColor:[UIColor blackColor] Tag:11 TextAlignment:NSTextAlignmentCenter textField:self.phoneField];
补充:设置输入框内文字数量的方法
//输入最大字节
- (void)textFiledDidChangeds:(UITextField *)textField {
//textField的tag值作为最大限制字节
if (textField.tag == 0)
return;
NSString *toBeString = textField.text;
NSString *lang = [[textField textInputMode] primaryLanguage]; // 键盘输入模式
if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,简体手写
//判断markedTextRange是不是为Nil,如果为Nil的话就说明你现在没有未选中的字符,
//可以计算文字长度。否则此时计算出来的字符长度可能不正确
UITextRange *selectedRange = [textField markedTextRange];
//获取高亮部分(感觉输入中文的时候才有)
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position) {
//中文和字符一起检测 中文是两个字符
if ([toBeString getStringLenthOfBytes] > textField.tag) {
textField.text = [toBeString subBytesOfstringToIndex:textField.tag];
}
}
} else {
if ([toBeString getStringLenthOfBytes] > textField.tag) {
textField.text = [toBeString subBytesOfstringToIndex:textField.tag];
}
}
}
网友评论