有的时候我们一些自己写的控件可能在以后的项目中会用到,这里我们就需要对其进行简单的封装就可以,方便以后的使用。

在许多视图中都会用到搜索框,接下来我们就一封装搜索框来说一下控件的封装。

//创建搜索框UITextField*searchBar=[[UITextFieldalloc]initWithFrame:CGRectMake(0,0,[UIScreenmainScreen].bounds.size.width,35)];searchBar.placeholder=@"大家都在搜";searchBar.font=[UiFontsystemFontSize:13];searchBar.background=[UIImagep_w_picpathWithStretchableName:@"图片.png"];//设置左边的viewUIImageView*p_w_picpathV;=[UIImageViewalloc]initWithImage:[UIImagep_w_picpathd:@"搜索图片"];//MysearchBar*p_w_picpathV;=[MysearchBaralloc]initWithImage:[UIImagep_w_picpathd:@"搜索图片"];p_w_picpathV.width+=10;p_w_picpathV.contentMode=searchBar.leftView=p_w_picpathV;//想要显示搜索框的视图,一定要设置左边视图的模式serchBar.leftViewMode=UITextFieldViewModeAlways;

//设置titleView为搜索框self.navigationItem.titleView=searchBar;


这样创建的搜索框是独立的,在每次使用到的时候都需要在写一遍,我们这里使用封装思想,因为这个搜索框继承自UITextField,所以我们写一个自己的MysearchBar继承自UITextField对其进行封装。

类中实现如下方法:

-(instancetype)initWithFrame:(CGRect)frame{if(self=[superinitWithFrame:frame]){//拷贝上面代码;只需要将searchBar改为self;searchBar.font=[UiFontsystemFontSize:13];searchBar.background=[UIImagep_w_picpathWithStretchableName:@"图片.png"];//设置左边的viewUIImageView*p_w_picpathV;=[UIImageViewalloc]initWithImage:[UIImagep_w_picpathd:@"搜索图片"];p_w_picpathV.width+=10;p_w_picpathV.contentMode=searchBar.leftView=p_w_picpathV;//想要显示搜索框的视图,一定要设置左边视图的模式serchBar.leftViewMode=UITextFieldViewModeAlways;}returnself;}


当我们再次使用搜索框的时候,我们之间使用自己封装的控件就行。如下所示:

-(void)viewDidlaod{[superviewDidlaod];MysearchBar*searchBar=[[MysearchBaralloc]initWithFrame:CGRectMake(0,0,[UIScreenmainScreen].bounds.size.width,35)];searchBar.placeholder=@"大家都在搜";//设置titleView为搜索框self.navigationItem.titleView=searchBar;}


这样就完成了一个控件的封装和调用。