轉載請注明部落格地址:https://blog.liuxia520.com/
今天要用 UITableView 做個列表分類,如果列表很多、而且 Section 名稱很長,用 Section 就不太直觀了。為節省時間上網搜了一下,發現大部分 demo 看起來麻煩、對原有程式碼改動較大,於是想要一個改動較小的下拉列表擴展實作,沒找到,只好自己動手實作。
既然要讓 Section 能下拉,就必須自己客製 Section。自訂的 SectionView 包含以下部分:
#import <UIKit/UIKit.h>
@protocol HeaderDropSectionDelegate;
@interface HeaderDropSection : UIButton
{
UIImageView *rightImageView;
BOOL _isOpen;
}
@property (nonatomic, assign) id<HeaderDropSectionDelegate> myDelegate;
@property (nonatomic, assign) int sectionIndex; // 該 SectionView 屬於哪個 section
@property (nonatomic, assign) BOOL isOpen; // 預設關閉
@property (nonatomic, strong) UILabel *sectionTitleLable; // 標題
@end
@protocol HeaderDropSectionDelegate <NSObject>
// section 點擊委託
- (void)HeaderDropSectionClick:(HeaderDropSection *)headerSectionView;
@end
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSArray *array = [orderInfoDic allKeys];
HeaderDropSection *headerDropView = [[HeaderDropSection alloc] initWithFrame:CGRectMake(0, 0, mTableView.frame.size.width, 60)];
headerDropView.sectionTitleLable.text = [array objectAtIndex:section];
headerDropView.myDelegate = self;
headerDropView.sectionIndex = section;
if (selectHeaderSectionIndex == section) {
[headerDropView setIsOpen:YES];
selectHeaderSectionIndex = section;
}
return headerDropView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 1;
}
然後在回傳 section 的代理中,只需增加一個判斷,原本的邏輯不需更動:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// 增加判斷:不顯示沒有展開的 section
if (section != selectHeaderSectionIndex) return 0;
// .........原有程式碼
}
-(void)HeaderDropSectionClick:(HeaderDropSection *)headerSectionView {
[headerSectionView setIsOpen:YES];
// 保存原本展開的 section
int oldIndex = selectHeaderSectionIndex;
if (oldIndex != -1) // 闔起之前已展開的 section
{
selectHeaderSectionIndex = -1;
[mTableView reloadSections:[NSIndexSet indexSetWithIndex:oldIndex] withRowAnimation:UITableViewRowAnimationFade];
}
// 若當前 section 不是展開的,則設為展開,否則闔起
if (headerSectionView.sectionIndex != oldIndex)
selectHeaderSectionIndex = headerSectionView.sectionIndex;
else
selectHeaderSectionIndex = -1;
// 刷新需要展開的 section
if (selectHeaderSectionIndex != -1) {
[mTableView reloadSections:[NSIndexSet indexSetWithIndex:selectHeaderSectionIndex] withRowAnimation:UITableViewRowAnimationFade];
}
}
對原本的程式碼加上以上部分,就可以實作 UITableView Section 下拉功能了。
註:變數 selectHeaderSectionIndex 用來保存當前正在展開的 section,沒有展開時為 -1。目前設計為同時只能有一個 section 展開;若需要多個 section 同時展開,可以用陣列保存需要展開的 selectHeaderSectionIndex。
由於是專案中的一個功能,原始碼就不上傳了,有空再補一個 demo。