iOS之单独使用UISearchBar创建搜索框的示例
程序员文章站
2023-12-20 12:07:58
这里实现的是进入页面后直接在导航栏上显示搜索框(包含右侧取消按钮),并弹出键盘且搜索框为直接可输入状态(第一响应者),点击右侧取消按钮后收起键盘并返回上一页。
搜索页...
这里实现的是进入页面后直接在导航栏上显示搜索框(包含右侧取消按钮),并弹出键盘且搜索框为直接可输入状态(第一响应者),点击右侧取消按钮后收起键盘并返回上一页。
搜索页面
1.实现代理uisearchbardelegate
@interface searchviewcontroller ()<uisearchbardelegate>
2.创建一个uisearchbar为属性
@property (nonatomic, strong) uisearchbar *searchbar;
3.进入页面后弹起键盘和离开页面前收起键盘
- (void)viewdidappear:(bool)animated { [super viewdidappear:animated]; if (!_searchbar.isfirstresponder) { [self.searchbar becomefirstresponder]; } } - (void)viewwilldisappear:(bool)animated { [super viewwilldisappear:animated]; [self.searchbar resignfirstresponder]; }
4.具体实现
- (void)setbarbuttonitem { //隐藏导航栏上的返回按钮 [self.navigationitem sethidesbackbutton:yes]; //用来放searchbar的view uiview *titleview = [[uiview alloc] initwithframe:cgrectmake(5, 7, self.view.frame.size.width, 30)]; //创建searchbar uisearchbar *searchbar = [[uisearchbar alloc] initwithframe:cgrectmake(0, 0, cgrectgetwidth(titleview.frame) - 15, 30)]; //默认提示文字 searchbar.placeholder = @"搜索内容"; //背景图片 searchbar.backgroundimage = [uiimage imagenamed:@"clearimage"]; //代理 searchbar.delegate = self; //显示右侧取消按钮 searchbar.showscancelbutton = yes; //光标颜色 searchbar.tintcolor = uicolorfromrgb(0x595959); //拿到searchbar的输入框 uitextfield *searchtextfield = [searchbar valueforkey:@"_searchfield"]; //字体大小 searchtextfield.font = [uifont systemfontofsize:15]; //输入框背景颜色 searchtextfield.backgroundcolor = [uicolor colorwithred:234/255.0 green:235/255.0 blue:237/255.0 alpha:1]; //拿到取消按钮 uibutton *canclebtn = [searchbar valueforkey:@"cancelbutton"]; //设置按钮上的文字 [canclebtn settitle:@"取消" forstate:uicontrolstatenormal]; //设置按钮上文字的颜色 [canclebtn settitlecolor:[uicolor whitecolor] forstate:uicontrolstatenormal]; [titleview addsubview:searchbar]; self.searchbar = searchbar; self.navigationitem.titleview = titleview; }
5.实现代理方法
#pragma mark - uisearchbardelegate - (bool)searchbarshouldbeginediting:(uisearchbar *)searchbar{ return yes; } - (void)searchbartextdidbeginediting:(uisearchbar *)searchbar { searchbar.showscancelbutton = yes; } - (void)searchbarsearchbuttonclicked:(uisearchbar *)searchbar { nslog(@"searchbutton"); } - (void)searchbarcancelbuttonclicked:(uisearchbar *)searchbar { [self.searchbar resignfirstresponder]; [self.navigationcontroller popviewcontrolleranimated:yes]; } - (void)searchbartextdidendediting:(uisearchbar *)searchbar { searchbar.showscancelbutton = yes; } - (void)searchbar:(uisearchbar *)searchbar textdidchange:(nsstring *)searchtext { nsstring *inputstr = searchtext; [self.results removeallobjects]; for (eldermodel *model in self.dataarray) { if ([model.name.lowercasestring rangeofstring:inputstr.lowercasestring].location != nsnotfound) { [self.results addobject:model]; } } [self.tableview reloaddata]; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。