2012-03-20 99 views
4

我正在嘗試自定義搜索欄。我已經想出瞭如何更改搜索欄中的背景和文本框,但是我無法找到更改欄中默認圖標的方法(放大鏡圖標)。iOS在搜索欄中更改圖標

有沒有辦法做到這一點?

回答

15

Open-source是你的朋友(就像可可,呵呵):

- (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]; 
    } 
} 

由於iOS的5.0:

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

完美!這正是我所期待的。非常感謝你!!! – KevinM 2012-03-20 21:29:23

+2

在iOS 7中,你應該爲'([[searchBar.subviews objectAtIndex:0]子視圖])中的'for(UIView * subview)',因爲現在有中間視圖 – 2013-12-25 16:05:52

+0

@Aurelien Porte,從iOs 5你應該使用官方方法:' - (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)圖標狀態:(UIControlState)狀態'它不適合你嗎? – 2013-12-26 10:26:51

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

Swift 3:'searchBar.setImage(UIImage(named:「tempUser」),用於:.search,state:.normal )' – 2017-11-22 21:57:19