UISearchBar由于不能知足项目需求进行了自定义UISearchBarcode
先实现功能,而后再进行封装it
考虑使用UITextField进行自定义io
出现了垂直方向的问题,查看UITextField的对齐方式,在UITextField的API中没有找到有关的方法,而后去其父类UIControl中查找class
找到了UIControlContentVerticalAlignment属性,能够调整垂直的样式import
查看UITextField的属性,有一个属性为leftView(若是没有能够考虑设置添加ImageView),设为UIImageView方法
须要修改leftViewMode 属性
im
封装后能够在其余地方使用
项目
#import <UIKit/UIKit.h> @interface HMSearchBar : UITextField + (instancetype)searchBar; @end
#import "HMSearchBar.h" @implementation HMSearchBar - (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的内容居中 leftView.contentMode = UIViewContentModeCenter; self.leftView = leftView; // 设置左边的view永远显示 self.leftViewMode = UITextFieldViewModeAlways; // 设置右边永远显示清除按钮 self.clearButtonMode = UITextFieldViewModeAlways; } return self; } + (instancetype)searchBar { return [[self alloc] init]; } @end