封裝SearchBar
+(instancetype)searchBar;
實現方法
+(instancetype)searchBar
{
return [[self alloc] init];
}
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 背景
self.background = [UIImage resizedImageWithName:@"searchbar_textfield_background"];
// 左邊的放大鏡圖標
UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"searchbar_textfield_search_icon"]];
iconView.contentMode = UIViewContentModeCenter;
self.leftView = iconView;
self.leftViewMode = UITextFieldViewModeAlways;
// 字體
self.font = [UIFont systemFontOfSize:13];
// 右邊的清除按鈕
self.clearButtonMode = UITextFieldViewModeAlways;
// 設置提醒文字
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSForegroundColorAttributeName] = [UIColor grayColor];
self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"搜索" attributes:attrs];
// 設置鍵盤右下角按鈕的樣式
self.returnKeyType = UIReturnKeySearch;
self.enablesReturnKeyAutomatically = YES;
}
return self;
}
-(void)layoutSubviews
{
[super layoutSubviews];
// 設置左邊圖標的frame
self.leftView.frame = CGRectMake(0, 0, 30, self.frame.size.height);
}
- 調用方法
SXWSearchBar *searchBar = [SXWSearchBar searchBar]; searchBar.frame = CGRectMake(0, 0, 300, 40); self.navigationItem.titleView = searchBar;