我尝试将 UITextField 子类化如下,以将自定义 rightView 实现为清除按钮:
I try to subclass UITextField as follows to implement custom rightView as a Clear button:
-(void) drawRect:(CGRect)rect
{
[self.layer setBackgroundColor:[[UIColor colorWithRed:20.0/255.0 green:20.0/255.0 blue:20.0/255.0 alpha:1] CGColor]];
[self.layer setCornerRadius:15.0];
UIImage *imgClear = [UIImage imageNamed:@"btnClear"];
CGSize iSize = [imgClear size];
UIButton *clearButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, iSize.width, iSize.height)];
[clearButton setImage:imgClear forState:UIControlStateNormal];
[clearButton addTarget:self action:@selector(clearText:) forControlEvents:UIControlEventTouchUpInside];
[self setRightViewMode:UITextFieldViewModeWhileEditing];
[self setRightView:clearButton];
[clearButton release];
}
但问题是:当文本字段刚刚成为焦点时,清除"按钮也变得可见,并且在我开始点击键盘后它消失了.有什么想法吗?
but the Problem is: when the textfield just becomes focus, "clear"-button becomes visible too and after i begin to tap the keyboard it dissapears. Any ideas?
我也遇到了同样的问题.我想这是一个 iOS 错误,但是,我尝试通过以下实现来解决这个问题,它对我来说很好.希望这会对你有所帮助.
I meet the same problem, too. I guess this is an iOS bug, however, I tried to fix this problem by following implementations and it works fine for me. Hope this will help you.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
...
[self addTarget:self action:@selector(onEditing:) forControlEvents: UIControlEventEditingChanged]
...
}
-(void) onEditing:(id)sender {
if(![self.text isEqualToString:@""]){
self.rightViewMode = UITextFieldViewModeAlways;
}else{
self.rightViewMode = UITextFieldViewModeNever;
}
}
- (BOOL)becomeFirstResponder{
BOOL ret = YES ;
ret = [super becomeFirstResponder] ;
if( ret & ![self.text isEqualToString:@""]){
self.rightViewMode = UITextFieldViewModeAlways;
}else{
self.rightViewMode = UITextFieldViewModeNever;
}
return ret ;
}
- (BOOL)resignFirstResponder
{
BOOL ret = YES ;
ret = [super resignFirstResponder] ;
if( ret )
self.rightViewMode = UITextFieldViewModeNever;
return ret ;
}
- (void) clearText:(id)sender
{
self.text = @"";
self.rightViewMode = UITextFieldViewModeNever;
}
这篇关于UITextField rightView "WhileEditing";问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!