当前位置: 移动技术网 > 移动技术>移动开发>IOS > 如何实现IOS_SearchBar搜索栏及关键字高亮

如何实现IOS_SearchBar搜索栏及关键字高亮

2019年07月24日  | 移动技术网移动技术  | 我要评论

搜索框的效果演示:

这个就是所谓的搜索框了,那么接下来我们看看如何使用代码来实现这个功能.

我所使用的数据是英雄联盟的英雄名单,是一个json数据的txt文件, json数据的处理代码如下所示:

//获取文件的路径path
nsstring *path = [[nsbundle mainbundle] pathforresource:@"heros" oftype:@"txt"];
//将路径下的文件转换成nsdata数据
nsdata *data = [nsdata datawithcontentsoffile:path];
//将得到的nsdata数据进行json解析并返回一个结果数组result
id result = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers error:nil];

我们再来看数据的层级关系:


这里解释下,这个层级关系是通过在线代码格式化网页得到的,我们上一步所做的数据处理就是将原始数据进行处理,得到一个结果数组,他的层级关系和格式化后一样,这样就可以根据格式化网页上的层级关系来进一步处理数据,将需要的内容放入数组或者字典(当然也可以直接打印result来看层级关系,看个人习惯).

那么我们所需要的内容就是字典中nick所对应的值,通过遍历将其取出来放入数组中,这里将这个数组定义为属性,在其他方法里会用到.

// 将搜索范围的内容放入数组
for (nsdictionary *diction in result) {
  [self.arrofseachboxes addobject:diction[@"nick"]];
 }

接下来我们创建一个uitableview用来显示数据,搜索条需要用到的类是uisearchcontroller,先看看如何创建:

系统的注释说的很清楚,如果想要在当前页显示搜索结果,这个方法的参数填nil即可,为了方便起见,声明一个uisearchcontroller的属性

@property (nonatomic, retain) uisearchcontroller *searchcontroller;

接下来是创建

// nil表示在当前页面显示搜索结果
self.searchcontroller = [[uisearchcontroller alloc] initwithsearchresultscontroller:nil];

uisearchcontroller头文件中被放在非常靠前的位置的是一个属性


根据字面意思我们可以猜到这跟搜索结果的更新有关,就跟tableviewreloaddata一个意思.那么很明显,我们得签协议<uisearchresultsupdating>,这个协议中只有一个必须要实现的方法.

- (void)updatesearchresultsforsearchcontroller:(uisearchcontroller *)searchcontroller;

头文件如下图所示:

---------这里是美丽的分割线---------

上面已经把所有关于搜索条的类和方法罗列了一下,下面来捋一捋

所有定义的属性如下所示:

ns_assume_nonnull_begin
@interface viewcontroller () <uitableviewdelegate, uitableviewdatasource, uisearchresultsupdating>
@property (nonatomic, retain) nsmutablearray *arrofseachboxes;/**< 搜索范围 */
@property (nonatomic, retain) nsmutablearray *arrofseachresults;/**< 搜索结果 */
@property (nonatomic, retain) uisearchcontroller *searchcontroller;
@property (nonatomic, retain) uitableview *tableview;
@end
ns_assume_nonnull_end

数据处理相关代码如下:

// 解析数据
nsstring *path = [[nsbundle mainbundle] pathforresource:@"heros" oftype:@"txt"];
nsdata *data = [nsdata datawithcontentsoffile:path];
id result = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers error:nil];
self.arrofseachboxes = [nsmutablearray array];
// 将搜索范围的内容放入数组
for (nsdictionary *dic in result) {
 [self.arrofseachboxes addobject:dic[@"nick"]];
}

和uisearchcontroller的创建相关代码如下:

// 创建
self.searchcontroller = [[uisearchcontroller alloc] initwithsearchresultscontroller:nil];

//searchbar的frame
self.searchcontroller.searchbar.frame = cgrectmake(0, 44, 0, 44);

// 是否需要在输入搜索内容时变暗
self.searchcontroller.dimsbackgroundduringpresentation = false;

self.searchcontroller.searchbar.showscancelbutton = yes;/**< 取消按钮 */

self.searchcontroller.searchresultsupdater = self;/**< 显示搜索结果的vc */

self.searchcontroller.active = yes;/**< 搜索结果显示 */

和tableview相关的代码如下:

// tableview
self.tableview = [[uitableview alloc] initwithframe:cgrectmake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height - 20) style:uitableviewstyleplain];

[self.view addsubview:self.tableview];

self.tableview.delegate = self;

self.tableview.datasource = self;

[self.tableview registerclass:[uitableviewcell class] forcellreuseidentifier:@"pool"];

//将searchbar放在tableview的头部视图 
self.tableview.tableheaderview = self.searchcontroller.searchbar;

uisearchresultsupdating协议方法代码如下:

- (void)updatesearchresultsforsearchcontroller:(uisearchcontroller *)searchcontroller {

//初始化存储搜索结果的数组
self.arrofseachresults = [nsmutablearray array];

// 获取关键字
nspredicate *predicate = [nspredicate predicatewithformat:@"self contains[c] %@", searchcontroller.searchbar.text];

// 用关键字过滤数组中的内容, 将过滤后的内容放入结果数组
self.arrofseachresults = [[self.arrofseachboxes filteredarrayusingpredicate:predicate] mutablecopy];

// 完成数据的过滤和存储后刷新tableview.
[self.tableview reloaddata];
}

tableview的datasource

- (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section {

// 显示搜索结果时
if (self.searchcontroller.active) {

 //以搜索结果的个数返回行数
 return self.arrofseachresults.count;
}
 //没有搜索时显示所有数据
 return self.arrofseachboxes.count;
}
- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath {

uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:@"pool"];

// 显示搜索结果时
if (self.searchcontroller.active) {

// 原始搜索结果字符串.
nsstring *originresult = self.arrofseachresults[indexpath.row];

// 获取关键字的位置
nsrange range = [originresult rangeofstring:self.searchcontroller.searchbar.text];

// 转换成可以操作的字符串类型.
nsmutableattributedstring *attribute = [[nsmutableattributedstring alloc] initwithstring:originresult];

// 添加属性(粗体)
[attribute addattribute:nsfontattributename value:[uifont systemfontofsize:20] range:range];

// 关键字高亮
[attribute addattribute:nsforegroundcolorattributename value:[uicolor redcolor] range:range];

// 将带属性的字符串添加到cell.textlabel上.
[cell.textlabel setattributedtext:attribute];

cell.textlabel.text = self.arrofseachresults[indexpath.row];

 } else {

 cell.textlabel.text = self.arrofseachboxes[indexpath.row];

  }

 return cell;
}

总结

以上就是如何实现ios搜索栏及搜索关键字高亮的全部内容,感兴趣的同学可以自己动手操作实现下,希望对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网