我有一个UISearchBar,想要移除搜索标记(放大镜图标),并将其替换为文本
我有一个UISearchBar,想要移除搜索标记(放大镜图标),并将其替换为文本
你可以使用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];
你可以通过以下方式更改放大图标,根据你的需求进行适应:
#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
对我有用 :)
如果你想要更加符合API规范的方法,可以使用普通的UITextField,并使用以下代码在UITextField中添加一个标签(如果你想要移除放大镜,那么你对搜索框有什么吸引力呢?):
UILabel *searchFieldLeftLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 32, 15)];
searchFieldLeftLabel.text = @"find:";
searchFieldLeftLabel.placeholder = @"e.g. wings, Boathouse";
searchFieldLeftLabel.font = [UIFont systemFontOfSize:14];
searchFieldLeftLabel.textColor = [UIColor grayColor];
self.searchFieldLeftLabel.leftView = locationSearchFieldLeftLabel;
[searchFieldLeftLabel release];