10

I want to be able to set my own image for the little magnifying glass icon on a UISearchBar. I'd also like to be able to move it around if possible. Any ideas? Currently, I only need support for iOS5 and above.

4

6 回答 6

34

对于支持 iOS 5 以上的应用程序,您可以使用以下方法来执行此操作,

- (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state; 

UIControlStateNormal并且UIControlStateDisabled是搜索栏的两种可能状态。

对于在此之前使用操作系统版本的应用程序,这将不起作用。您可能必须UISearchbar通过枚举子视图来创建一个类别并更改图标。

于 2012-11-17T06:42:13.667 回答
13

如果您只想更改默认放大图标的颜色,可以将图像设置为使用模板模式,然后设置图像视图的 tintColor。

if ([view isKindOfClass:[UITextField class]]) {
    UITextField *textField = (id)view;

    UIImageView *iconView = (id)textField.leftView;
    iconView.image = [iconView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    iconView.tintColor = <##dimmedColor##>;

    // other styling:
    textField.font = <##font##>;
    textField.textColor = <##activeColor##>;
    textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:<##searchBar##>.placeholder
                                                                      attributes:@{NSForegroundColorAttributeName: <##dimmedColor##>}];
}
于 2014-04-07T08:59:56.457 回答
2

对于斯威夫特:-

UISearchBar.appearance().setImage(UIImage(named: "new_search_icon"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal)
于 2016-02-10T12:23:58.247 回答
0

利用

- (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state;
于 2012-11-21T20:56:03.823 回答
0

对于斯威夫特 5

  searchBar.setImage(UIImage(named: "your_favicon"), for: .search, state: .normal)
于 2020-06-30T06:28:50.830 回答
-2

尝试打印所有子视图... iOS 独立。

for (id obj in _SearchBar.subviews) {
  NSLog(@"%@", obj);

  if ( [obj isKindOfClass:[UIImage class]] )  {
     NSLog(@"probably found...");

     UIImage *img = obj;
     [img setImage....];
  }
}
于 2012-11-17T07:48:42.257 回答