使用UITextField自定义UISearchBar
有的时候,使用iOS自带的控件不符合我们的开发要求时,我们一般自定义控件来满足需求。在此处,我们通过创建一个GUSearchBar类,继承自UITextField类来自定义搜索框。
创建GUSearchBar
代码如下:GUSearchBar.h
1 2 3 4 5 6
| #import <UIKit/UIKit.h> @interface GUSearchBar : UITextField
+(instancetype) searchBar;
@end
|
GUSearchBar.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| #import "GUSearchBar.h"
@implementation GUSearchBar
-(id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) {
self.background = [UIImage resizedImage:@"searchbar_textfield_background"]; self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; UIImageView *leftView = [[UIImageView alloc] init]; leftView.image = [UIImage imageWithName:@"searchbar_textfield_search_icon"];
leftView.width = leftView.image.size.width + 10; leftView.height = leftView.image.size.height; leftView.contentMode = UIViewContentModeCenter; self.leftView = leftView; self.leftViewMode = UITextFieldViewModeAlways; self.clearButtonMode = UITextFieldViewModeAlways; self.placeholder = @"搜索"; } return self; }
+(instancetype) searchBar { return [[self alloc] init]; }
@end
|
注意:上述有类似leftView.width,leftView.height这样的语法是使用了自定义UIView的扩展分类,详情请点击UIView扩展。
使用
1 2 3 4 5
| GUSearchBar *searchBar = [[GUSearchBar alloc] init]; searchBar.width = 350; searchBar.height = 30; self.navigationItem.titleView = searchBar;
|
使用效果