简单实现UITableView索引功能(中英文首字母索引)(一) ByH罗

相关类:

NSString+PinYing(获取中英文首字母)   参考上面链接

#import "ViewController.h"
#import "contactModel.h"
#import "NSArray+ContactArray.h"
#define kScreen_Height ([UIScreen mainScreen].bounds.size.height)
#define kScreen_Width ([UIScreen mainScreen].bounds.size.width)
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchDisplayDelegate>

@property(nonatomic,strong)  UITableView *tableView;
@property(nonatomic,strong) NSMutableArray *dataArray;
@property(nonatomic,strong) NSArray *indexArray; @property(nonatomic,strong) UISearchBar *searchBar;
@property(nonatomic,strong) UISearchDisplayController *mSearchDisplayController;
@property(nonatomic,strong) NSMutableArray *filteredPersons; //搜索过滤后 搜索结果 @end
@implementation ViewControlle
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.title=@"索引"; NSArray *array=@[
@{@"contact":@"lulu",
@"conatctUrl":@"147456140992" },
@{ @"contact":@"哈尼",
@"conatctUrl":@"189234342"},
@{ @"contact":@"陆军",
@"conatctUrl":@"15475654785"},
@{ @"contact":@"是的",
@"conatctUrl":@"1873895343"},
@{ @"contact":@"身份",
@"conatctUrl":@"15688382345"},
@{ @"contact":@"爱德华",
@"conatctUrl":@"14754565443"},
];
_filteredPersons = [NSMutableArray array];
_dataArray=[NSMutableArray array];
for (NSDictionary *dict in array) {
contactModel *model = [[contactModel alloc] init];
model.contactName=dict[@"contact"];
model.contactUrl=dict[@"conatctUrl"];
[_dataArray addObject:model];
} //索引
self.indexArray=[self.dataArray arrayWithPinYinFirstLetter]; [self.view addSubview:self.tableView];
self.tableView.tableHeaderView=self.searchBar;
self.tableView.tableFooterView=[[UIView alloc]init];
self.tableView.keyboardDismissMode=UIScrollViewKeyboardDismissModeOnDrag; self.mSearchDisplayController.searchResultsTableView.tableFooterView=[[UIView alloc]init];//隐藏多余分割线
} -(UISearchBar *)searchBar
{
if (!_searchBar) {
_searchBar = [[UISearchBar alloc] init];
_searchBar.delegate = self;
_searchBar.placeholder = @"搜索";
[_searchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[_searchBar sizeToFit];
_searchBar.barTintColor=[UIColor redColor];
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:@"取消"];
}
return _searchBar;
} -(UISearchDisplayController *)mSearchDisplayController
{
if (!_mSearchDisplayController) {
_mSearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
_mSearchDisplayController.searchResultsDelegate = self;
_mSearchDisplayController.searchResultsDataSource = self;
_mSearchDisplayController.delegate = self;
}
return _mSearchDisplayController;
} #pragma mark----CreatMyCustomTablevIew-----
-(UITableView *)tableView
{
if (!_tableView) {
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,kScreen_Width, kScreen_Height) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"REUSE_CELLID"];
_tableView.contentSize=CGSizeMake(kScreen_Width,kScreen_Height*2);
_tableView.sectionIndexBackgroundColor=[UIColor clearColor];//索引背景色
_tableView.sectionIndexColor=[UIColor redColor];//索引背景色
}
return _tableView;
}
//在tableview中有多少个分组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableView==self.tableView) {
return self.indexArray.count;
}
return 1;
} #pragma mark--- UITableViewDataSource and UITableViewDelegate Methods---
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.mSearchDisplayController.searchResultsTableView)
{
//否则显示搜索出来的数据
return [self.filteredPersons count];
}
NSDictionary *dict = self.indexArray[section];
return [dict[@"content"] count];
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
contactModel *model;
if (tableView == self.mSearchDisplayController.searchResultsTableView)
{
model = [self.filteredPersons objectAtIndex:indexPath.row];
}else{
NSDictionary *dict = self.indexArray[indexPath.section];
model=dict[@"content"][indexPath.row];
}
cell.textLabel.text=model.contactName;
cell.detailTextLabel.text=model.contactUrl;
return cell;
} -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50;
} #pragma ---索引
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if (tableView==self.tableView) {
NSDictionary *dict = self.indexArray[section];
NSString *title =[NSString stringWithFormat:@" %@",dict[@"firstLetter"]];
return title;
}
return nil;
} //设置表格的索引数组
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
if (tableView==self.tableView) {
NSMutableArray *resultArray =[NSMutableArray arrayWithObject:UITableViewIndexSearch];
for (NSDictionary *dict in self.indexArray) {
NSString *title = dict[@"firstLetter"];
[resultArray addObject:title];
}
return resultArray;
}
return 0;
} - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
if ([title isEqualToString:UITableViewIndexSearch])
{
[tableView setContentOffset:CGPointZero animated:NO];//tabview移至顶部
return NSNotFound;
}
else
{
return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index]; // -1 because we add the search symbol
}
}
#pragma --搜索
#pragma mark - UISearchDisplayDelegate
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString {
//一旦SearchBar输入內容有变化,则执行这个方法,请问要不要重裝searchResultTableView的数据
[self filterContentForSearchText:searchString
scope:[self.searchBar scopeButtonTitles][self.searchBar.selectedScopeButtonIndex]]; return YES;
} - (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchScope:(NSInteger)searchOption
{
//如果设置了选项,当Scope Button选项有变化的时候,则执行这个方法,请问要不要重裝searchResultTableView的数据
[self filterContentForSearchText:self.searchBar.text
scope:self.searchBar.scopeButtonTitles[searchOption]];
return YES;
} //源字符串内容是否包含或等于要搜索的字符串内容
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
if ([searchText length]==0) {
return;
}
NSString * regex = @"(^[0-9]+$)";
NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL isNum=[pred evaluateWithObject:searchText];//判断是否是数字
NSMutableArray *tempResults = [NSMutableArray array];
NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
for (int i = 0; i < self.dataArray.count; i++) {
contactModel *model=self.dataArray[i];
NSString *storeString;
if (isNum) {
storeString =model.contactUrl;
}else{
storeString =model.contactName;
}
/*匹配的规则是:源字符串内容是否包含或等于要搜索的字符串内容*/
NSRange storeRange = NSMakeRange(0, storeString.length);
NSRange foundRange = [storeString rangeOfString:searchText options:searchOptions range:storeRange];
if (foundRange.length) {
[tempResults addObject:model];
}
//把一个数组的值赋给 self.filteredPersons
[self.filteredPersons removeAllObjects];
[self.filteredPersons addObjectsFromArray:tempResults];
}
} -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"indexPath===%ld",indexPath.row);
contactModel *model;
if (tableView==self.mSearchDisplayController.searchResultsTableView){
model =self.filteredPersons[indexPath.row];
}else{
NSDictionary *dict = self.indexArray[indexPath.section-1];
NSArray *modeArr=dict[@"content"];
model = modeArr[indexPath.row];
}
}

Demo:https://files.cnblogs.com/files/sixindev/tableviewIndex.zip

简单实现UITableView索引功能(中英文首字母索引) (二) By HL的更多相关文章

  1. 简单实现UITableView索引功能(中英文首字母索引)(一) ByH罗

    UITableView索引功能是常见的,主要是获取中英文的首字母并排序,系统自带获取首字母 //系统获取首字母 - (NSString *) pinyinFirstLetter:(NSString*) ...

  2. HBuilder+eclipse开发:使用ajax异步传值生成首字母索引

    使用ajax异步传值生成首字母索引大致有以下几个步骤: 1.服务器端使用servlet提取出数据库里的数据; 2.使用首字母工具类对数据进处理得到首字母; 3.再将首字母和数据一一对应存入json数组 ...

  3. 分享一份550多个Linux命令的文档,按照命令首字母索引排序

    输入一个命令,让我给你一个关于它的完美解释! 众所周知,Linux命令是IT人必须掌握的一个技能,有了它,我们可以部署和维护各种各样的服务和应用.但是,大部分的Linux命令我们不一定记得住,而别是各 ...

  4. PHP提取中英文首字母的方法(首字母索引)

    function Getzimu($str) { $str= iconv("UTF-8","gb2312", $str);//如果程序是gbk的,此行就要注释掉 ...

  5. 微信小程序通讯录首字母索引效果,车辆品牌选择列表

    效果图: wxml代码: <block wx:for="{{list}}"> <view class='letter' id="letter{{inde ...

  6. 做个简单的Android列表字母索引控件

    相信大家在许多App中都见到过带字母索引的界面,比如我最近看到的这个开源控件: WaveSideBar 很酷是不是?!!!如果加在例如联系人列表界面上,大大提升了用户体验. 那么这个索引控件要怎么做呢 ...

  7. iOS开发——UI_swift篇&UITableView实现索引功能

    UITableView实现索引功能     关于UItableView的索引在平时项目中所见不多,最多的就是跟联系人有关的界面,虽然如此,但是作为一个swift开发的程序必须知道的一个技术点,所以今天 ...

  8. IOS开发中实现UITableView按照首字母将集合进行检索分组

    在开发公司项目中遇到了将图书目录进行按照首字母分组排序的问题 1.在项目添加解析汉字拼音的Pinyin.h文件 /* * pinyin.c */ #define HANZI_START 19968 # ...

  9. 联系人的侧边字母索引ListView 将手机通讯录姓名通过首字母排序。

      package com.lixu.letterlistview; import java.util.ArrayList; import java.util.List; import org.apa ...

随机推荐

  1. 编写Java程序,随机给定一个数字猜大小

    返回本章节 返回作业目录 需求说明: 由系统随机生成一个1~100之间的整数. 通过控制台一直输入一个整数,比较该数与系统随机生成的那个数,如果大就输出"猜大了.",继续输入:如果 ...

  2. 论文翻译:2020_Acoustic Echo Cancellation Based on Recurrent Neural Network

    论文地址:https://ieeexplore.ieee.org/abstract/document/9306224 基于RNN的回声消除 摘要 本文提出了一种基于深度学习的语音分离技术的回声消除方法 ...

  3. YangTools从YANG生成Java类(Maven)

    1.说明 ODL提供了Yang Tools工具从YANG文件生成Java类, 本文介绍使用Maven插件的方式生成, 基于yang-maven-plugin这个插件. 2.创建Maven工程 Ecli ...

  4. [GDOI2021 Day2T1] 宝石

    题目大意 \(n\)个点的树, 树上每一个点有一个宝石\(w_i\), 给出一个固定的数字不重复的序列\(p_i\)和一些询问\(u_i, v_i\), 对于每一个询问求出\(u_i\)到\(v_i\ ...

  5. MongoDB与微服务

    1. 微服务的优势 * 开发速度快 * 变化响应快 * 易维护 * 扩容简单2. 微服务架构设计要素 * 服务解耦(Decouple) * HTTP API - 简单接口(Dumb Pipes) * ...

  6. Linux 安装并启用 PHP-FPM

    首先,在编译时带上 --enable-fpm 参数: [root@localhost local]# yum -y install libxml2 libxml2-devel gd gd-devel ...

  7. Bom 基本使用以及定时器 倒计时案例

    BOM 是浏览器对象模型 它提供了独立内容而与浏览器窗口进行交互的对象,其核心对象是window 窗口加载事件 注意:window.onload 就可以吧JS代码写在页面元素的上方,因为onload是 ...

  8. sqlcl - Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file

    运行sqlcl的命令sql出错 bash-4.2$ sql username/password@hostname:1521:databasename Exception in thread " ...

  9. 本地Java大数据环境基础配置(Maven)

    注:图片如果损坏,点击文章链接:https://www.toutiao.com/i6812623309138559500/ 创建项目 准备pom.xml文件配置(附在文档最后) 在下载jar过程中极其 ...

  10. Java对象内存模型

    2 Java对象内存模型 在HotSpot虚拟机中,对象在内存中存储的布局可以分为3块区域:对象头(Header). 实例数据(Instance Data)和对齐填充(Padding). 在 JVM ...