搜索栏中的iOS更改图标

Kev*_*inM 4 icons uikit uisearchbar ios

我正在尝试自定义搜索栏.我已经想出如何更改搜索栏中的背景和文本框,但我找不到更改栏中默认图标的方法(放大玻璃图标).

有没有办法做到这一点?

A-L*_*ive 15

开源是你的朋友(就像可可一样,呵呵):

- (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];
  }  
}
Run Code Online (Sandbox Code Playgroud)

自iOS 5.0起:

[self.testSearchBar setImage:[UIImage imageNamed: @"favicon.png"]
            forSearchBarIcon:UISearchBarIconSearch
                       state:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

  • 任何人都知道我需要用来替换的图像大小,例如搜索图标图像?我正在使用图像= 64x64像素和图像@ 2x = 128x128但它比原始图像小. (4认同)
  • 在iOS 7中,你应该做`for([[searchBar.subviews objectAtIndex:0]子视图]中的UIView*子视图))因为现在有一个中间视图 (2认同)