iOS Change icon in the search bar

2019-05-06 05:08发布

问题:

I'm trying to customize a search bar. I've figured out how to change the background and the text box within the search bar, but I can't find a way to change the icon that is default in the bar (the magnify glass icon).

Is there a way to do this?

回答1:

Open-source is your friend (just like cocoa is, huh):

- (void)setSearchIconToFavicon {
  // Really a UISearchBarTextField, but the header is private.
  UITextField *searchField = nil;
  for (UIView *subview in searchBar.subviews) {
    if ([subview isKindOfClass:[UITextField class]]) {
      searchField = (UITextField *)subview;
      break;
    }
  }

  if (searchField) {  
    UIImage *image = [UIImage imageNamed: @"favicon.png"];
    UIImageView *iView = [[UIImageView alloc] initWithImage:image];
    searchField.leftView = iView;
    [iView release];
  }  
}

Since iOS 5.0:

[self.testSearchBar setImage:[UIImage imageNamed: @"favicon.png"]
            forSearchBarIcon:UISearchBarIconSearch
                       state:UIControlStateNormal];


回答2:

searchBar.setImage(UIImage(named: "tempUser")!,
                forSearchBarIcon: UISearchBarIcon.Search, 
                           state: UIControlState.Normal)