Search code examples
ios7uisearchbartextfieldrightview

Unable to set rightview or leftview in textfield of searchbar in ios 7


Purpose: I want to set right view as label in searchbar's textfield

Following Code working fine in ios 6 for doing the same thing:

UISearchBar  *search = [[UISearchBar alloc] init];
[search setTintColor:[UIColor grayColor]];
search.frame = CGRectMake(0, 150, 320,50);
search.delegate = self;

UITextField *searchField=[search.subviews objectAtIndex:1];//Changed this line in ios 7
searchField.backgroundColor=[UIColor redColor];

UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
label.text=@"Hello";
label.textColor=[UIColor greenColor];

searchField.rightView = label;
searchField.rightViewMode = UITextFieldViewModeAlways;

[self addSubView:search];

When i have Run the same code in ios 7(with xcode 7.0.2 fully updated), It was giving me error, after googling i got that hiearchy of searchbar to textfield has been changed, so i have modified my code as:

replaced commented line in above code with:

UITextField *searchField=[((UIView *)[search.subviews objectAtIndex:0]).subviews lastObject];

after doing this, it is not giving me any error(also checked the logs by printing the description of textfield and everything is working good), when i run it, it gives textfield with red background but the rightView's label is not shown to me. Now, can anyone help me how to show this rightview.


Solution

  • If you want to do this programatically then you have to declare UISearchBar object in your .h file.

    UISearchBar  *searchBar;
    

    And in your .m file you can code like:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        // Do any additional setup after loading the view, typically from a nib.
        searchBar = [[UISearchBar alloc] init];
        [searchBar setTintColor:[UIColor grayColor]];
        searchBar.frame = CGRectMake(0, 150, 320,50);
        searchBar.delegate = self;
    
        [self.view addSubview:searchBar];
    }
    
    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
    
        UITextField *searchField;
        if ([[[UIDevice currentDevice] systemVersion] floatValue]<7.0)
            searchField=[searchBar.subviews objectAtIndex:1];
        else
            searchField=[((UIView *)[searchBar.subviews objectAtIndex:0]).subviews lastObject];
    
        searchField.backgroundColor=[UIColor redColor];
    
        UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        label.text=@"Hello";
        label.textColor=[UIColor greenColor];
    
        searchField.rightView = label;
        searchField.rightViewMode = UITextFieldViewModeAlways;
    }
    

    I think this will work for both iOS7 and prior versions of iOS7.