iOS新手入门常见问题5-UITableViewController添加列表上的搜索栏

2016年08月20日 iOS 16条评论 阅读4731次

本篇说的是利用UISearchController实现UITableViewController顶部的搜索功能。

自从iOS8以后, 苹果官方已经推荐我们使用UISearchController来代替UISearchBar+UISearchDisplayController的组合方式了,同时协议也要更变为UISearchResultsUpdating了。

声明UISearchController对象及协议

@interface ViewController : UITableViewController<UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) NSArray *searchResultList;
@property (nonatomic, strong) NSArray *originalList;
@end 

上面的代码完成了指定协议和增加变量的功能

初始化UISearchController对象

下面需要自己初始化一下UISearchController ,一般在viewDidLoad方法中完成

// 参数传递为nil,表示使用当前自身ViewController作为搜索结果显示的界面
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.tableView.tableHeaderView = self.searchController.searchBar; 

添加UISearchResultsUpdating协议实现的方法

初始化并太添加给tableView的头布局之后,接下来就要实现UISearchResultsUpdating中声明的协议了。 协议中方法只有一个:

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = [self.searchController.searchBar text];
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
    if (self.searchResultList!= nil) {
        [self.searchResultList removeAllObjects];
    }
    // 从原始数据中筛选数据
    self.searchResultList= [NSMutableArray arrayWithArray:[self.originalList filteredArrayUsingPredicate:preicate]];
    // 刷新表格
    [self.tableView reloadData];
} 

上面协议方法中用到了一个叫做NSPredicate的东西,实现类似sql语句的功能,详细内容自行网络获取吧。

让UITabeleView显示搜索后的数据

通过协议方法筛选得到新的数据list之后,画面上UITableViewController上要显示的行数以及每行显示数据都要发生改变了。 可以通过searchController.active进行判断当前是显示着原始数据还是搜素结果的数据:

下面就利用这个属性来重新修改一下UITableViewController相关的协议方法。

// 设置区域要显示的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchController.active) {
        return [self.searchResultList.count];
    } else {
        return [self.originalList.count];
    }
}
// 返回每行单元格的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *id = @"CellID";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:id];
    if (cell == nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:id];
    }
    if (self.searchController.active) {
        // get data using self.searchResultList[indexPath.row];
    } else {
        // get data using self.originalList[indexPath.row];
    }
    return cell;
} 

如果有点击每个单元格后进入下一个详细画面的转场,还要在- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender方法中修改要传递给目标画面的数据。

TableView搜索栏转场到下一画面后仍显示

最后,会发现一个问题,就是点击单元格转场到下一个画面后,下一个画面还会显示着前一个画面的搜索栏以及输入法。这时需要在前一个画面(UITableViewController)的viewWillDisappear方法中添加对searchBar进行remove的逻辑处理。

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
} 
分享本文至:

WRITTEN BY

avatar
看了本文是不是觉得很赞,那就赶紧点击下面按钮分享给身边的朋友吧!

16 条评论

  1. <a href="http://www.onewebsql.net/under-armour-curry-one-tutti-rosa-butye">under armour curry one tutti rosa</a> <a href="http://www.onlinne.net/nike-zoom-pegasus-34-gris-p%C3%BArpura-kurpesc">nike zoom pegasus 34 gris p煤rpura</a> <a href="http://www.onpointsports.net/curry-2-gr%C3%A5-storm-butya">curry 2 gr氓 storm</a> <a href="http://www.oqibo.net/air-jordan-17-low-svart-chrome-parts-schuheg">air jordan 17 low svart chrome parts</a> <a href="http://www.ourjourneychurch.net/adidas-neo-campus-svart-gr%C3%A5-butyf">adidas neo campus svart gr氓</a> <a href="http://www.ouverturefacile.net/nike-free-inneva-for-vendita-butya">nike free inneva for vendita</a>
    weheartwebsites http://www.weheartwebsites.net/

  2. avatar footprintsrv

    <a href="http://www.afrikose.com/roshe-run-baskets-iron-vert-seaweed-obuvb">roshe run baskets iron vert seaweed</a> <a href="http://www.bartezloudge.com/nike-dunk-low-wei%C3%9F-rot-chaussuresc">nike dunk low wei脽 rot</a> <a href="http://www.buenostokio.com/air-jordan-retro-13-chicago-kurpesg">air jordan retro 13 chicago</a> <a href="http://www.cmlyon.com/air-jordan-retro-6-marrone-verde-schuhea">air jordan retro 6 marrone verde</a> <a href="http://www.dafpme.com/soccer-boots-adidas-x-15.3-meteor-turf-orange-jaune-noir-butyf">soccer boots adidas x 15.3 meteor turf orange jaune noir</a> <a href="http://www.earinfectionn.com/adidas-superstar-rosa-blomst-kurpesc">adidas superstar rosa blomst</a>
    footprintsrv http://www.footprintsrv.com/

  3. avatar gdcxwzrzpt

    <a href="http://www.mysonno.com/ralph-lauren-short-sleeved-polo-pony-dark-bl%C3%A5-polot">ralph lauren short sleeved polo pony dark bl氓</a> <a href="http://www.ncctifton.com/portugal-19-mario-rui-away-soccer-country-jersey-nflx">portugal 19 mario rui away soccer country jersey</a> <a href="http://www.juleefashion.com/kobe-7-midnight-azul-kurpesc">kobe 7 midnight azul</a> <a href="http://www.lovedbyfew.com/nfl-mark-barron-womens-limited-camo-jersey-26-los-angeles-rams-nike-rush-realtree-nflz">nfl mark barron womens limited camo jersey 26 los angeles rams nike rush realtree</a> <a href="http://www.lupazul.com/nike-free-run-5.0-dahombres-schwarz-obuve">nike free run 5.0 dahombres schwarz</a> <a href="http://www.ouaias.com/nike-air-max-r%C3%B8d-foot-locker-scarpec">nike air max r酶d foot locker</a>
    gdcxwzrzpt http://www.gdcxwzrzpt.com/

  4. avatar uv喷绘

    文章不错

  5. avatar freizeittrend

    <a href="http://www.evolutionecig.com/nike-kd-vii-big-b%C3%B8rn-gr%C3%A5-sort-schuheb">nike kd vii big b酶rn gr氓 sort</a> <a href="http://www.georginabauer.com/cubs-34-jon-lester-blue-2016-world-series-champions-pullover-mlb-hoodie-nflu">cubs 34 jon lester blue 2016 world series champions pullover mlb hoodie</a> <a href="http://www.bootsoffprice.com/nike-air-force-1-mid-black-red-white-skou">nike air force 1 mid black red white</a> <a href="http://www.theprintjobs.com/jordan-4-gs-white-cement-runninge">jordan 4 gs white cement</a> <a href="http://www.dbajournal.com/kaki-volt-nikelab-acg-zapatosu">kaki volt nikelab acg</a> <a href="http://www.procomedian.com/hombres-salomon-s-lab-sense-rojo-blanco-chaussuresa">hombres salomon s lab sense rojo blanco</a>
    freizeittrend http://www.freizeittrend.com/

  6. avatar hvactampafl

    <a href="http://www.horecasummit.com/kobe-11-yeezy-sneakerg">kobe 11 yeezy</a> <a href="http://www.hntonghetang.com/hermes-inspired-h-bracelet-hermesr">hermes inspired h bracelet</a> <a href="http://www.carlandcodys.com/nike-air-force-1-puerto-rico-sko-shoesv">nike air force 1 puerto rico sko</a> <a href="http://www.deploygis.com/coach-tote-rose-international-coachc">coach tote rose international</a> <a href="http://www.amitsrl.com/billig-nike-free-2.0-dam%C3%A4nner-grau-shoesc">billig nike free 2.0 dam盲nner grau</a> <a href="http://www.rahsaskatoon.com/mens-nike-air-force-1-mid-casual-shoes-skos">mens nike air force 1 mid casual shoes</a>
    hvactampafl http://www.hvactampafl.com/

  7. avatar mailstraight

    <a href="http://www.tipicousa.com/nike-flyknit-lunar-3-herre-s%C3%B8lv-skoa">nike flyknit lunar 3 herre s酶lv</a> <a href="http://www.reprebates.com/the-hermes-scarf-book-scarfr">the hermes scarf book</a> <a href="http://www.goeaglepointe.com/grey-mens-nike-roshe-yeezy-boost-shoes-sneakere">grey mens nike roshe yeezy boost shoes</a> <a href="http://www.ykloans.com/nike-mercurical-victory-vi-tf-purple-orange-black-soccer-cleats-shoesa">nike mercurical victory vi tf purple orange black soccer cleats</a> <a href="http://www.servicioswom.com/oakley-holbrook-sunglasses-clear-sunglassesr">oakley holbrook sunglasses clear</a> <a href="http://www.drlunaworld.com/ralph-lauren-yarmouth-shirt-size-guide-quiz-test-polod">ralph lauren yarmouth shirt size guide quiz test</a>
    [url=http://www.mailstraight.com/]mailstraight[/url]

  8. avatar ridderdrive

    <a href="http://www.divasdelface.com/new-york-yankees-cap-green-screen-hatg">new york yankees cap green screen</a> <a href="http://www.whitegayshop.com/ray-ban-sunglasses-prices-jordan-games-sunglassesf">ray ban sunglasses prices jordan games</a> <a href="http://www.beautyestyle.com/black-and-purple-nike-air-max-2017-skox">black and purple nike air max 2017</a> <a href="http://www.safeonproject.com/air-jordan-9-menns-bl%C3%A5-skoc">air jordan 9 menns bl氓</a> <a href="http://www.gagnetoo.com/air-jordan-retro-1-low-og-white-skob">air jordan retro 1 low og white</a> <a href="http://www.epiuenergia.com/adidas-superstar-2-light-blau-shoesv">adidas superstar 2 light blau</a>
    ridderdrive http://www.ridderdrive.com/

  9. avatar 77衣都穿衣打扮

    菜鸟来学习了

  10. avatar 深圳装修公司

    很难的说,只会简单的PHP啊啊。

  11. avatar 威客众包

    谢谢博主分享,学习啦

  12. avatar 烟台网络公司

    不许哦,顶一个!

欢迎留言




用户登录

sitemap