Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField rightView "WhileEditing" problem

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?

like image 459
Andrey Gershengoren Avatar asked Aug 23 '11 18:08

Andrey Gershengoren


2 Answers

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;
}
like image 80
Redbug Avatar answered Sep 29 '22 11:09

Redbug


You shoud use : [self setRightViewMode:UITextFieldViewModeAlways];

like image 42
hustwcw Avatar answered Sep 29 '22 12:09

hustwcw