轉載請註明我部落格的地址:http://blog.liuxia520.com/
今天要使用UITableView做個列表分類的,如果列表很多,而且Section名稱還很長的話,使用Section就不是很直觀了。為了節省時間,就在網上搜了下,發現大部分的demo看起來麻煩,對我原有的代碼修改比較大,就想找個對我代碼修改較少的UITableView下拉式清單擴充實現,不過沒找到,只好自己動手實現了。
第一步:
既然要使sectino能下拉,那麼必須要自己定製section了,所以我定製的sectinoView包含以下部分
#import @protocol HeaderDropSectionDelegate;@interface HeaderDropSection : UIButton{ UIImageView *rightImageView; BOOL _isOpen;}@property(nonatomic,assign)id myDelegate;@property(nonatomic,assign)int sectionIndex;//該SectionView屬於哪個section@property(nonatomic,assign)BOOL isOpen;//預設關閉@property(nonatomic,strong)UILabel *sectionTitleLable;//標題@end@protocol HeaderDropSectionDelegate //section點擊委託-(void)HeaderDropSectionClick:(HeaderDropSection *)headerSectionView;@end
第二步:
設定UITableView Section 的代理
- (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
{
//增加判斷
if(section!=selectHeaderSectionIndex)returnNewLostHt3930NewLostHt;//不顯示沒有展開的
//.................原有的代碼
}
第三步:
實現自訂section的代理
-(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展開,如果需要多個seciton都能展開,可以使用數組儲存需要展開的selectHeaderSectionIndex 。
由於是項目中得一個功能,所以源碼就不上傳了。有時間的補一個demo