背景:
当UITextField
的rightView
被占用的时候,clearButtonMode
就失效了,这时就需要自定制一个clearBtn
了,要想实现和系统clearBtn一样的效果还得多调试一下,下面是我写好的跟系统一样效果的代码:
//遵守协议
<UITextFieldDelegate>
//创建clearBtn
UIView * phoneRight = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100*ScaleX+30, 40*ScaleX)];
UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[clearBtn addTarget:self action:@selector(clearAction) forControlEvents:UIControlEventTouchUpInside];
[clearBtn setImage:[UIImage imageNamed:@"clearImg"] forState:UIControlStateNormal];
clearBtn.frame = CGRectMake(5, 15, 15, 15);
[phoneRight addSubview:clearBtn];
self.clearBtn = clearBtn;
self.clearBtn.hidden = YES;
//textField 设置代理
_phoneTF.delegate = self;
//添加点击事件
- (void)clearAction {
_phoneTF.text = @"";
self.clearBtn.hidden = YES;
}
#pragma mark =============== UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
if ([textField isEqual:_phoneTF] && textField.text.length > 0) {
self.clearBtn.hidden = NO;
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([textField isEqual:_phoneTF]) {
if (range.location == 0 && range.length == 1 && string.length == 0) {
self.clearBtn.hidden = YES;
}else if (range.location > 0 || range.length > 0 || string.length > 0) {
self.clearBtn.hidden = NO;
}
}
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
if ([textField isEqual:_phoneTF]) {
self.clearBtn.hidden = YES;
}
return YES;
}