Customizing UISearch bar

257 views Asked by At

I am trying to customize my search bar like this enter image description here

So far I have managed to do upto this

enter image description here Now I need to know how to add image on right side, shaping the corners and changing background to an image. This is my code so far. I can do this with help of UITextField but I want to do this using the UISearchBar. Any help??

   - (void)setSearchIconToFavicon 
    {  
        // commented are the things I tried out 
        UITextField *searchField = nil;  
        for (UIView *subview in searchBar.subviews)
        {    
            if ([subview isKindOfClass:[UITextField class]]) 
            {      
                searchField = (UITextField *)subview;      
                break;    
            }  
        }    
        if (searchField) 
        {      
            UIImage *image = [UIImage imageNamed: @"search_btn.png"];   
            UIImageView *iView = [[UIImageView alloc] initWithImage:image]; 
            //UIImage *image2 = [UIImage imageNamed: @"search_next_btn.png"];   
            //UIImageView *iView2 = [[UIImageView alloc] initWithImage:image2];  
            searchField.leftView = iView;    
            //searchField.rightView=iView2;
            [[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
            searchField.textColor = [UIColor grayColor];
        }  
  }
2

There are 2 answers

1
Dharmbir Singh On

You can replace the Bookmark image instead, and adjust its offset if necessary.Like this..

[self.searchDisplayController.searchBar setImage:[UIImage imageNamed:@"yourImage"] forSearchBarIcon:UISearchBarIconBookmark state:UIControlStateNormal];
[self.searchDisplayController.searchBar setPositionAdjustment:UIOffsetMake(0, 0) forSearchBarIcon:UISearchBarIconBookmark];

And you can handle the button event in the delegate method:

- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar

i Hope you got my point.

1
iEinstein On

You can this line of code if your target application is >=5.0 to change background image of search bar.

[[UISearchBar appearance] setSearchFieldBackgroundImage:[UIImage imageNamed:@"searchbar.png"]forState:UIControlStateNormal];