欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS tableView实现搜索功能

程序员文章站 2023-12-19 22:20:46
本文实例为大家分享了tableview搜索功能的具体代码,供大家参考,具体内容如下 框架:https://github.com/honeycao/hcsortandsea...

本文实例为大家分享了tableview搜索功能的具体代码,供大家参考,具体内容如下

框架:https://github.com/honeycao/hcsortandsearchdemo

github里面有详细的说明

支持中文排序

#import "chinesetopinyin.h"
#import "hcsortstring.h"
#import "wlccitytvc.h"
#import "wlcprovincemodel.h"
#import "zypinyinsearch.h"

#define reusedid @"citycell"

@interface wlccitytvc () <uitableviewdelegate, uitableviewdatasource, uisearchresultsupdating>
/**
 * 存放城市字典的数组,后来也存放排序后的
 */
@property (nonatomic, strong) nsmutablearray* cityarrm;
@property (nonatomic, strong) wlcuser* user;
/**
 * 存放首字母的数组
 */
@property (nonatomic, strong) nsmutablearray* letterarrm;
@property (nonatomic, strong) nsmutablearray* wordarr;
/**
 * 存放城市模型的数组
 */
@property (nonatomic, strong) nsmutablearray* modelarrm;
@property (strong, nonatomic) nsmutablearray* searchdatasource; /**<搜索结果数据源*/
@property (strong, nonatomic) uisearchcontroller* searchcontroller;
@end

@implementation wlccitytvc

- (void)viewdidload
{
 [super viewdidload];
 [self setupui];
}

#pragma mark - navitionbarbackbaritem返回事件
- (bool)navigationshouldpoponbackbutton
{
 self.searchcontroller.active = no;
 return yes;
}


- (void)didreceivememorywarning
{
 [super didreceivememorywarning];
 // dispose of any resources that can be recreated.
}

- (wlcuser*)user
{
 if (nil == _user) {
  _user = [nskeyedunarchiver unarchiveobjectwithfile:fileuser];
 }
 return _user;
}

- (nsmutablearray*)cityarrm
{
 if (nil == _cityarrm) {
  _cityarrm = [nsmutablearray array];
 }
 return _cityarrm;
}

- (nsmutablearray*)wordarr
{
 if (nil == _wordarr) {
  _wordarr = [nsmutablearray array];
 }
 return _wordarr;
}

- (nsmutablearray*)letterarrm
{
 if (nil == _letterarrm) {
  _letterarrm = [nsmutablearray array];
 }
 return _letterarrm;
}

- (uisearchcontroller*)searchcontroller
{
 if (!_searchcontroller) {
  _searchcontroller = [[uisearchcontroller alloc] initwithsearchresultscontroller:nil];
  _searchcontroller.searchresultsupdater = self;
  _searchcontroller.dimsbackgroundduringpresentation = no;
  _searchcontroller.hidesnavigationbarduringpresentation = no;
  _searchcontroller.searchbar.placeholder = @"搜索";
    _searchcontroller.searchbar.tintcolor = [uicolor whitecolor];
  [_searchcontroller.searchbar sizetofit];
 }
 return _searchcontroller;
}

- (nsmutablearray*)modelarrm
{
 if (nil == _modelarrm) {
  _modelarrm = [nsmutablearray array];
  for (nsarray* temparr in self.cityarrm) {
   for (nsdictionary* dict in temparr) {
    [wlcprovincemodel setupreplacedkeyfrompropertyname:^nsdictionary* {
     return @{
      @"pid" : @"id"
     };
    }];
    wlcprovincemodel* model = [wlcprovincemodel objectwithkeyvalues:dict];
    [_modelarrm addobject:model];
   }
  }
 }
 return _modelarrm;
}

- (nsmutablearray*)searchdatasource
{
 if (nil == _searchdatasource) {
  _searchdatasource = [nsmutablearray array];
 }
 return _searchdatasource;
}

- (void)setupui
{
 self.tableview.backgroundcolor = [uicolor rgb:234 andgreen:234 andblue:243];
 [self getallcities];
 self.tableview.delegate = self;
 self.tableview.datasource = self;
 self.tableview.tablefooterview = [[uiview alloc] init];
}

- (void)getallcities
{
 nsstring* url = [kurl stringbyappendingstring:@"promary/"];
 url = [url stringbyappendingstring:self.cityid];
 url = [url stringbyappendingstring:@"/city"];
 [svprogresshud showwithstatus:@"获取城市中"];
 [netrequesttool requestwithparamsdict:nil image:nil name:nil token:self.user.token value:nil hearerfield:nil url:url type:get successblock:^(afhttprequestoperation* _nonnull operation, id _nonnull responseobject) {
  nsstring* errnum = [nsstring stringwithformat:@"%@", responseobject[@"errnum"]];
  if ([errnum isequaltostring:@"1"]) {
   [svprogresshud setminimumdismisstimeinterval:2.5];
   [svprogresshud showinfowithstatus:[nsstring stringwithformat:@"%@", responseobject[@"retmsg"]]];
   [self.navigationcontroller popviewcontrolleranimated:yes];
  }
  else {
   [svprogresshud dismiss];
   @try {
    self.cityarrm = responseobject[@"retdata"];
    nsmutablearray* cityarrm = [nsmutablearray array];
    for (nsmutabledictionary* citydic in self.cityarrm) {
     [cityarrm addobject:[citydic objectforkey:@"name"]];
     nsmutabledictionary* dictm = [nsmutabledictionary dictionarywithdictionary:citydic];
     [self preparecitylistdatasourcewitharray:cityarrm andtodictionary:dictm];
    }
    self.cityarrm = [self sortarray:self.wordarr];

   } @catch (nsexception* exception) {

   } @finally {
    [self.tableview settableheaderview:self.searchcontroller.searchbar];
    [self.tableview reloaddata];
   }
  }

 }
  anderrorblock:^(afhttprequestoperation* _nonnull operation, nserror* _nonnull error) {
   wlog(@"error == %@", error);
   [svprogresshud showerrorwithstatus:@"获取省份失败,请稍后重试"];
   [self.navigationcontroller popviewcontrolleranimated:yes];
  }];
}

#pragma mark -排序城市
- (void)preparecitylistdatasourcewitharray:(nsarray*)array andtodictionary:(nsmutabledictionary*)dic
{
 for (nsstring* city in array) {

  nsstring* citypinyin = [chinesetopinyin pinyinfromchinisestring:city];
  if ([city isequaltostring:@"重庆"]) {
   citypinyin = @"chongqing";
  }

  nsstring* firstletter = [citypinyin substringwithrange:nsmakerange(0, 1)];

  if (![dic objectforkey:firstletter]) {
   //   nsmutablearray* arr = [nsmutablearray array];
   //   [dic setvalue:firstletter forkey:@"letter"];
   dic[@"letter"] = firstletter;
  }
  if ([[dic objectforkey:firstletter] containsobject:city]) {
   return;
  }
 }

 [self.wordarr addobject:dic];

 //  [self.wordarr addobjectsfromarray:[[dic allvalues] sortedarrayusingselector:@selector(compare:)]];
}

/**
 * 排序并按首字母分组
 *
 * @param arraytosort <#arraytosort description#>
 *
 * @return <#return value description#>
 */
- (nsmutablearray*)sortarray:(nsmutablearray*)arraytosort
{
 nsmutablearray* arrayforarrays = [[nsmutablearray alloc] init];

 //根据拼音对数组排序
 nsarray* sortdescriptors = [nsarray arraywithobject:[nssortdescriptor sortdescriptorwithkey:@"letter" ascending:yes]];
 //排序
 [arraytosort sortusingdescriptors:sortdescriptors];

 nsmutablearray* temparray = nil;
 bool flag = no;

 //分组
 for (int i = 0; i < arraytosort.count; i++) {
  nsstring* pinyin = [arraytosort[i] objectforkey:@"letter"];
  nsstring* firstchar = [pinyin substringtoindex:1];
  //  nslog(@"%@",firstchar);
  if (![self.letterarrm containsobject:[firstchar uppercasestring]]) {
   [self.letterarrm addobject:[firstchar uppercasestring]];
   temparray = [[nsmutablearray alloc] init];
   flag = no;
  }
  if ([self.letterarrm containsobject:[firstchar uppercasestring]]) {
   [temparray addobject:arraytosort[i]];
   if (flag == no) {
    [arrayforarrays addobject:temparray];
    flag = yes;
   }
  }
 }

 return arrayforarrays;
}

//让cell下划线左对齐
- (void)tableview:(uitableview*)tableview willdisplaycell:(uitableviewcell*)cell forrowatindexpath:(nsindexpath*)indexpath
{
 if ([cell respondstoselector:@selector(setseparatorinset:)]) {
  [cell setseparatorinset:uiedgeinsetsmake(0, 0, 0, 0)];
 }
 if ([cell respondstoselector:@selector(setpreservessuperviewlayoutmargins:)]) {
  [cell setpreservessuperviewlayoutmargins:no];
 }
 if ([cell respondstoselector:@selector(setlayoutmargins:)]) {
  [cell setlayoutmargins:uiedgeinsetszero];
 }
}

#pragma mark - tableview's delegate and datasource
- (nsinteger)numberofsectionsintableview:(uitableview*)tableview
{
 if (!self.searchcontroller.active) {
  return self.letterarrm.count;
 }
 else {
  return 1;
 }
}

- (nsinteger)tableview:(uitableview*)tableview numberofrowsinsection:(nsinteger)section
{
 if (!self.searchcontroller.active) {
  return [self.cityarrm[section] count];
 }
 else {
  return self.searchdatasource.count;
 }
}

- (uitableviewcell*)tableview:(uitableview*)tableview cellforrowatindexpath:(nsindexpath*)indexpath
{
 uitableviewcell* cell = [tableview dequeuereusablecellwithidentifier:reusedid];
 if (!cell) {
  cell = [[uitableviewcell alloc] initwithstyle:uitableviewcellstyledefault reuseidentifier:reusedid];
 }
 @try {
  if (!self.searchcontroller.active) {
   nsdictionary* dict = self.cityarrm[indexpath.section][indexpath.row];
   cell.textlabel.text = [nsstring stringwithformat:@"%@", dict[@"name"]];
  }
  else {
   //   nsdictionary* dict = self.searchdatasource[indexpath.row];
   wlcprovincemodel* model = self.searchdatasource[indexpath.row];
   cell.textlabel.text = [nsstring stringwithformat:@"%@", model.name];
  }
 } @catch (nsexception* exception) {

 } @finally {
 }
 return cell;
}

- (nsstring*)tableview:(uitableview*)tableview titleforheaderinsection:(nsinteger)section
{
 if (!self.searchcontroller.active) {
  return [self.letterarrm objectatindex:section];
 }
 else
  return nil;
}
- (nsarray*)sectionindextitlesfortableview:(uitableview*)tableview
{
 if (!self.searchcontroller.active) {
  return self.letterarrm;
 }
 else
  return nil;
}

- (void)tableview:(uitableview*)tableview didselectrowatindexpath:(nsindexpath*)indexpath
{

 nsdictionary* dict;
 @try {
  if (!self.searchcontroller.active) {
   dict = self.cityarrm[indexpath.section][indexpath.row];
  }
  else {
   wlcprovincemodel* model = self.searchdatasource[indexpath.row];
   dict = [nsdictionary dictionarywithobjects:@[ model.name, model.pid ] forkeys:@[ @"name", @"id" ]];
  }

  [[nsnotificationcenter defaultcenter] postnotificationname:@"citychoosed" object:self userinfo:dict];
 } @catch (nsexception* exception) {
 } @finally {
 }
 self.searchcontroller.active = no;
 [self.navigationcontroller poptoviewcontroller:self.fathervc animated:yes];
 [tableview deselectrowatindexpath:indexpath animated:yes];
}

#pragma mark - uisearchdelegate
- (void)updatesearchresultsforsearchcontroller:(uisearchcontroller*)searchcontroller
{
 [self.searchdatasource removeallobjects];
 nsarray* ary = [nsarray new];
 //对排序好的数据进行搜索
 nsdictionary* alldatasource = [hcsortstring sortandgroupforarray:self.modelarrm propertyname:@"name"];
 ary = [hcsortstring getallvaluesfromdict:alldatasource];

 if (searchcontroller.searchbar.text.length == 0) {
  [self.searchdatasource addobjectsfromarray:ary];
 }
 else {
  ary = [zypinyinsearch searchwithoriginalarray:ary andsearchtext:searchcontroller.searchbar.text andsearchbypropertyname:@"name"];
  [self.searchdatasource addobjectsfromarray:ary];
 }
 [self.tableview reloaddata];
}

@end

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: