如何更改UISearchBar以用文本replace文本字段内的search图标

我有UISearchBar,我想删除search标记(放大镜图标),并放置一个文本,而不是它

您可以按照以下方式更改magnify图标,以适应您的需求: –

#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 

它为我工作:)

你可以使用UIAppearance方法

Swift 3.0

 UISearchBar.appearance().setImage(UIImage(named: "image_name"), for: .search, state: .normal) 

Objective-C的

 [[UISearchBar appearance] setImage:[UIImage imageNamed:@"image_name"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal]; 

API更友好的一点是使用一个普通的UITextField,用下面的代码在UITextField中添加一个标签(如果你想删除放大镜,那你对search框有什么吸引力?):

 UILabel *searchFieldLeftLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 32, 15)]; searchFieldLeftLabel.text = @"find:"; searchFieldLeftLabel.placeholder = @"eg wings, Boathouse"; searchFieldLeftLabel.font = [UIFont systemFontOfSize:14]; searchFieldLeftLabel.textColor = [UIColor grayColor]; self.searchFieldLeftLabel.leftView = locationSearchFieldLeftLabel; [searchFieldLeftLabel release]; 

结果是一个不错的文本框,看起来像:

在这里输入图像说明

而当你开始input文字时,它将取代占位符,但标签仍然是:

在这里输入图像说明

看到这篇文章删除UISearchbar左侧的图像 。 没有公共API来更改或删除放大镜,你应该只使用UITextField。