更改UISearchBar上的放大镜图标

10 iphone search objective-c uisearchbar

我希望能够为UISearchBar上的小放大镜图标设置我自己的图像.如果可能的话,我也希望能够移动它.有任何想法吗?目前,我只需要支持iOS5及以上版本.

iDe*_*Dev 34

对于支持iOS 5及更高版本的应用,您可以使用以下方法执行此操作,

- (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state; 
Run Code Online (Sandbox Code Playgroud)

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

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


Yan*_*yer 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##>}];
}
Run Code Online (Sandbox Code Playgroud)