,,,,有的时候我们一些自己写的控件可能在以后的项目中会用的到,这里我们就需要对其进行简单的封装就可以,方便以后的使用。
,,,,在许多视图中都会用到搜索框,接下来我们就一封装搜索框来说一下控件的封装。
//创建搜索框 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”);//设置左边的观点 时间=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中)框架 { ,,如果(self =, (super initWithFrame:帧)){//拷贝上面代码,只需要将searchBar改为自我; ,,,,,,,searchBar.font =(UiFont systemFontSize: 13); ,,,,,,,,,,,searchBar.background =, (UIImage p_w_picpathWithStretchableName: @”图片. png”);//设置左边的观点 ,,,,,,,,,,,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 才能;自我; }
当我们再次使用搜索框的时候,我们之间使用自己封装的控件就行。如下所示:
- (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; }
这样就完成了一个控件的封装和调用。