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

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

//创建搜索框
UITextField* searchBar = [[UITextField alloc]initWithFrame:CGRectMake(0,0,[UIScreen
 mainScreen].bounds.size.width,35)];
searchBar.placeholder =@"大家都在搜";
searchBar.font =[UiFont systemFontSize:13];
searchBar.background = [UIImage p_w_picpathWithStretchableName:@"图片.png"];
//设置左边的view
UIImageView* p_w_picpathV;= [UIImageView alloc]initWithImage:[UIImage p_w_picpathd:@"搜索图片"];
//MysearchBar* p_w_picpathV;= [MysearchBar alloc]initWithImage:[UIImage p_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 = [super initWithFrame:frame]){
//拷贝上面代码;只需要将searchBar改为self;
        searchBar.font =[UiFont systemFontSize:13];
            searchBar.background = [UIImage p_w_picpathWithStretchableName:@"图片.png"];
//设置左边的view
            UIImageView* p_w_picpathV;= [UIImageView alloc]initWithImage:[UIImage p_w_picpathd:@"搜索图片"];
        p_w_picpathV.width +=10;
        p_w_picpathV.contentMode = searchBar.leftView = p_w_picpathV;
//想要显示搜索框的视图,一定要设置左边视图的模式
           serchBar.leftViewMode = UITextFieldViewModeAlways;
    }
  return self;
}


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

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


这样就完成了一个控件的封装和调用。iphone中自定义控件的封装_封装控件