如何更改UISearchBar中的搜索图标?

时间:2014-07-24 01:49:59

标签: objective-c ios7 uisearchbar

我正在尝试更改iOS7中UISearchBar内的搜索图标,好吧,我明白了。但这是最好的方法吗?

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

问题是图像尺寸不如原版,我想知道更换图像的正确尺寸。我正在使用图像= 64x64和图像@ 2x = 128x128,这是正确的吗?如果是这样,为什么我的搜索栏是这样的:

SearchBar Icon Issue

2 个答案:

答案 0 :(得分:2)

您可以通过设置searchField的leftView来实现此目的

if let textFieldInsideSearchBar = self.searchBar.valueForKey("searchField") as? UITextField {
   textFieldInsideSearchBar.leftView = imageView
}

答案 1 :(得分:1)

使用此代码替换iPhone UISearchBar中的放大镜图标

#import <UIKit/UIKit.h>

@interface SearchBoxExperimentsViewController : UIViewController {
  IBOutlet UISearchBar *searchBar;
}

@end




#import "SearchBoxExperimentsViewController.h"

@interface SearchBoxExperimentsViewController (Private)
- (void)setSearchIconToFavicon;
@end


@implementation SearchBoxExperimentsViewController

- (void)viewDidLoad {
  [self setSearchIconToFavicon];
  [super viewDidLoad];
}

#pragma mark Private

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

@end