Sunday, June 2, 2013

UITextField rightViewMode example in Objective C (iOS).


UITextField rightViewMode

Controls when the right overlay view appears in the text field.

@property(nonatomic) UITextFieldViewMode rightViewMode

Discussion of [UITextField rightViewMode]
The default value for this property is UITextFieldViewModeNever.

UITextField rightViewMode example.
//add button to address bar
//UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
UIButton *refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, height)]
[refreshButton setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
[refreshButton setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateHighlighted];
refreshButton.imageEdgeInsets = UIEdgeInsetsMake(0, -16, 0, 0);
[refreshButton addTarget:self action:@selector(refresh) forControlEvents:UIControlEventTouchUpInside];
addressBar.rightView = refreshButton;
addressBar.rightViewMode = UITextFieldViewModeUnlessEditing;

Example of [UITextField rightViewMode].
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@\"RefreshIcon.png\"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@\"RefreshIcon.png\"] forState:UIControlStateHighlighted];
button.imageEdgeInsets = UIEdgeInsetsMake(0, -16, 0, 0);
[button addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventTouchUpInside];
addressBar.rightView = button;
addressBar.rightViewMode = UITextFieldViewModeAlways;

UITextField rightViewMode example.
- (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;
}

End of UITextField rightViewMode example article.