Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField rightViewMode odd behaviour

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:

  • Shows while focused and no text
  • Shows while focused and typing
  • Hides when no focus

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.

like image 373
Andy Smart Avatar asked Sep 13 '11 11:09

Andy Smart


2 Answers

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.

like image 64
Tof Avatar answered Nov 13 '22 20:11

Tof


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).

like image 1
breakp01nt Avatar answered Nov 13 '22 21:11

breakp01nt