UITableView字母索引視圖(仿微信)
我們?cè)谑褂肬ITableView時(shí)边酒,會(huì)一個(gè)自帶的字母索引視圖。但是設(shè)計(jì)要求字母要在滑動(dòng)列表的上層,類似下圖:
于是康震,我自己寫(xiě)了一個(gè)蛛芥,如下效果:
要實(shí)現(xiàn)的效果:
1提鸟、列表在滑動(dòng)時(shí),右側(cè)的字母索引視圖會(huì)根據(jù)當(dāng)前列表的組來(lái)進(jìn)行變化仅淑;
2称勋、在字母索引視圖上可以點(diǎn)擊跳到對(duì)應(yīng)的字母組,并且可以手指滑動(dòng)選擇涯竟,在點(diǎn)擊或者滑動(dòng)過(guò)程中赡鲜,有一個(gè)指示器視圖顯示當(dāng)前選中的組的字母。
我的實(shí)現(xiàn)方式:
1庐船、字母索引視圖采用UIControl類银酬,命名為IndexView(IndexView實(shí)現(xiàn)UITableViewDelegate, UITableViewDataSource兩個(gè)協(xié)議),因?yàn)閁IControl有以下三個(gè)方法可以用來(lái)識(shí)別手勢(shì):
//當(dāng)手指開(kāi)始觸摸屏幕時(shí)
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(nullable UIEvent *)event;
//當(dāng)手指在屏幕上移動(dòng)時(shí)
- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(nullable UIEvent *)event;
//當(dāng)手指離開(kāi)屏幕時(shí)
- (void)endTrackingWithTouch:(nullable UITouch *)touch withEvent:(nullable UIEvent *)event;
2筐钟、將UITableView的delegate和dataSource設(shè)置為IndexView揩瞪,并且IndexView提供兩個(gè)代理方法:IndexViewDelegate和IndexViewDataSource。
這樣做的目的主要是為了獲取到UITableView的代理方法返回的數(shù)據(jù)(如果讀者有更好的方式篓冲,歡迎在評(píng)論區(qū)給我留言?? )李破。
具體代理方法如下:
/** 代理方法 */
@protocol IndexViewDelegate <NSObject>
@optional
- (void)tableView:(UITableView *_Nonnull)tableView didSelectRowAtIndexPath:(NSIndexPath *_Nullable)indexPath;
- (CGFloat)tableView:(UITableView *_Nullable)tableView heightForHeaderInSection:(NSInteger)section;
- (nullable UIView *)tableView:(UITableView *_Nullable)tableView viewForHeaderInSection:(NSInteger)section;
@required
/** 當(dāng)前選中下標(biāo) */
- (void)selectedSectionIndexTitle:(NSString *_Nullable)title atIndex:(NSInteger)index;
/** 添加指示器視圖 */
- (void)addIndicatorView:(UIView *_Nullable)view;
@end
/** 數(shù)據(jù)源方法 */
@protocol IndexViewDataSource <NSObject>
@required
- (NSInteger)tableView:(UITableView *_Nullable)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *_Nullable)tableView:(UITableView *_Nonnull)tableView cellForRowAtIndexPath:(NSIndexPath *_Nullable)indexPath;
- (NSInteger)numberOfSectionsInTableView:(UITableView *_Nullable)tableView;
/** 組標(biāo)題數(shù)組 */
- (NSArray<NSString *> *_Nullable)sectionIndexTitles;
@end
3、使用纹因,UIViewController只需要實(shí)現(xiàn)如下3個(gè)代理方法即可:
#pragma mark - IndexView
- (NSArray<NSString *> *)sectionIndexTitles {
//去掉搜索符號(hào)
NSMutableArray *resultArray = [NSMutableArray array];//[NSMutableArray arrayWithObject:UITableViewIndexSearch];
for (NSDictionary *dict in self.brandArray) {
NSString *title = dict[@"firstLetter"];
[resultArray addObject:title];
}
return resultArray;
}
//當(dāng)前選中組
- (void)selectedSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
[self.demoTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:NO];
}
//將指示器視圖添加到當(dāng)前視圖上
- (void)addIndicatorView:(UIView *)view {
[self.view addSubview:view];
}
2017.06.20 更新
1喷屋、新增搜索
2、修正手指移動(dòng)到視圖外瞭恰,指示器視圖不消失的問(wèn)題(感謝評(píng)論區(qū)指正??)