简单实现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. JDK、JVM和JRE三者间的关系,及JDK安装路径下的文件夹说明

    JDK的全称是Java SE Development Kit, 即Java标准开发包,是Sun公司提供的一套用于开发Java应用程序的开发包, 它提供了编译.运行Java查询所需的各种工具和资源,包括 ...

  2. 编写Java程序,实现控制台版的省市联动

    返回本章节 返回作业目录 需求说明: 系统显示用户所有直辖市的名称,用户在控制台输入直辖市的名称,即可在控制台中显示该直辖市所管辖的所有区的名称. 实现思路: 创建省市联动类ProvincialLin ...

  3. ComfortTypingPro快速录入工具

    1.简介 Comfort Typing Pro 官方中文注册版是一款非常方便的键盘快速录入辅助工具, 也可以叫做键盘宏工具吧. 程序的主要功能是可以帮助你快速的输入大量需要重复输入的内容, 支持文本和 ...

  4. Tool_BurpSuite安装和简单使用

    一.安装 1.检查Java环境 Burp Suite是用Java语言开发的,运行时依赖于JRE,因此需要先配置Java环境.在CMD中输入java -version 出现下图的结果,证明已配置Java ...

  5. Python中*args 和**kwargs作为形参和实参时的功能详解

    *args 和**kwargs作为形参 *args 和**kwargs作为形参被称为不定长参数,用来处理超出必备参数部分的参数.注意:args和kwargs可以修改为其它变量名. 必备参数就是在定义函 ...

  6. MySQL 表字段唯一性约束设置方法unique

    1. 建表时加上唯一性约束 CREATE TABLE `t_user` ( `Id` int(11) NOT NULL AUTO_INCREMENT, -- 自增 `username` varchar ...

  7. vue3.0+vite+ts项目搭建-postcss-pxtorem 实现移动自适应(五)

    这里不考虑大屏,所以不做amfe-flexible的配置 首先是安装依赖 yarn add postcss-loader postcss-pxtorem -D yarn add autoprefixe ...

  8. css画叉叉(一般用于关闭按钮)

    css 一般用于右上角关闭弹窗 #pdclose { width: 18px; height: 18px; cursor: pointer; float: right; position: relat ...

  9. Centos7安装erlang以及RabbitMQ Centos启动rabbitmq

    本文使用版本:  rabbitmq-server-3.8.3-1.el7.noarch.rpm   Centos7  erlang  22.3.1 在线安装 yum install esl-erlan ...

  10. 五天学完MySQL打卡挑战 day01

    明天继续上传学习笔记和练习的Word文档 晚安~