搜索框继承于UITextField
@interface WZSearchBar : UITextField
@end
注意:一个拉伸不变形的问题。
+(instancetype)resizeableImageWithName:(NSString *)imageName
{
UIImage *image = [UIImage imageWithName:imageName];
CGFloat left = image.size.width * 0.5;
CGFloat top = image.size.height * 0.5;
//实现拉伸不变形
image = [image stretchableImageWithLeftCapWidth:left topCapHeight:top];
return image;
}
@implementation WZSearchBar
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
//设置背景图片
self.background = [UIImage resizeableImageWithName:@"searchbar_textfield_background"];
//设置文本垂直居中
self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
//设置清除按钮
self.clearButtonMode = UITextFieldViewModeWhileEditing;
//添加放大镜到搜索框上
UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"searchbar_textfield_search_icon"]];
self.leftView = iv;
self.leftViewMode = UITextFieldViewModeAlways;
CGRect frame = iv.frame;
frame.size.width = 40;
iv.frame = frame;
iv.contentMode = UIViewContentModeCenter;
//设置默认提示问题
self.placeholder = @"亲,请输入要搜索的内容~";
self.frame = CGRectMake(0, 0, 300, 35);
}
return self;
}
@end
另外要注意的一个问题:
WZSearchBar *searchBar = [[WZSearchBar alloc] init];
searchBar.placeholder = @"亲~请输入要搜索的内容~";
//注意:如果控件是添加到导航条上作为导航条的titleView,设置Frame的x,y无效
searchBar.frame = CGRectMake(0, 0, 300, 35);
self.navigationItem.titleView = searchBar;