//创建textField
UITextField *searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(30*SCREEN_SCALE, 0, backView.width-30*SCREEN_SCALE, backView.height)];
searchTextField.borderStyle = UITextBorderStyleNone;searchTextField.backgroundColor = [UIColor whiteColor];
UIColor *color = RGB(153, 153, 153);
UIFont * font = [UIFont systemFontOfSize:15];
searchTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"请输入关键字", nil) attributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName: font}];
//输入监听
[searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
//自定义右侧删除按钮
UIView * rightView = [[UIView alloc]initWithFrame:CGRectMake(searchTextField.width - self.height-2, (searchTextField.height-50*SCREEN_SCALE)/2, 60*SCREEN_SCALE, 50*SCREEN_SCALE)];
rightView.backgroundColor = [UIColor whiteColor];
rightView.userInteractionEnabled = YES;
UIImageView *rightImageView = [[UIImageView alloc]initWithFrame:CGRectMake(8*SCREEN_SCALE, 0, 44*SCREEN_SCALE, 44*SCREEN_SCALE)];
rightImageView.image = [UIImage imageNamed:@"ic_close_searach"];
rightImageView.userInteractionEnabled = YES;
[rightView addSubview:rightImageView];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImageView:)];
[rightImageView addGestureRecognizer:tap];
searchTextField.rightView = rightView;
searchTextField.rightViewMode = UITextFieldViewModeAlways;
[backView addSubview:searchTextField];
self.searchTextField = searchTextField;
#pragma mark - 输入字符限制
- (void)textFieldDidChange:(UITextField *)textField
{
NSString *toBeString = textField.text;
NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,简体手写
UITextRange *selectedRange = [textField markedTextRange];
//获取高亮部分
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position) {
if (toBeString.length > kMaxLength/2) {
textField.text = [toBeString substringToIndex:kMaxLength/2];
[DialogUtil showDialogWithImage:nil andMessage:NSLocalizedString(@"文字不能超过30个字符", nil)];
}
}
// 有高亮选择的字符串,则暂不对文字进行统计和限制
else{
}
}
// 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
else{
if (toBeString.length > kMaxLength) {
textField.text = [toBeString substringToIndex:kMaxLength];
[DialogUtil showDialogWithImage:nil andMessage:NSLocalizedString(@"字符不能超过30个字符", nil)];
}
}
}