I'm adding a custom clear button (UIButton) to a UITextField as the rightView, however I've found there's some weird behaviour on the viewMode. It doesn't seem to display as the normal clear button does, despite the view mode being set. Example code below:
UITextField *f = [[[UITextField alloc] init] autorelease];
f.frame = CGRectMake(0, 0, 300, 44);
f.backgroundColor = [UIColor clearColor];
f.textColor = [UIColor whiteColor];
f.clearButtonMode = UITextFieldViewModeNever;
UIImage *image = [UIImage imageNamed:@"Image.png"];
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
b.frame = CGRectMake(0, 0, image.size.width, image.size.height);
[b setImage:image forState:UIControlStateNormal];
f.rightView = b;
f.rightViewMode = UITextFieldViewModeWhileEditing;
The button displays correctly in the following states:
However, if the textfield already has content, and you switch focus to it the clear button does not show. To get it to show again you must delete all text, and switch focus back and forth.
I haven't found anyone else with this problem, so have been scratching my head on this one for a while. Any light shedding very much appreciated.
This fixes the bug :
- (BOOL)becomeFirstResponder
{
BOOL ret = YES ;
ret = [super becomeFirstResponder] ;
if( ret && ( _setupClearButtonMode == UITextFieldViewModeWhileEditing ) )
self.rightViewMode = UITextFieldViewModeAlways ;
return ret ;
}
- (BOOL)resignFirstResponder
{
BOOL ret = YES ;
ret = [super resignFirstResponder] ;
if( ret && ( _setupClearButtonMode == UITextFieldViewModeWhileEditing ) )
self.rightViewMode = UITextFieldViewModeWhileEditing ;
return ret ;
}
In your subclass of UITextField with the var _setupClearButtonMode set on init.
I recently ran into the same problem and ended up setting right view mode to UITextFieldViewModeAlways and manually showing/hiding that button when it's needed (made proxy delegate which monitored text field state, set button's visibility and passed messages to actual delegate).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With