前言
在之前的文章中有寫過,如何在ViewController中使用靜態(tài)TableView 這樣我們可以在任何一個(gè)界面中嵌套一個(gè)靜態(tài)的tableView,大大的提高了界面的開發(fā)效率。
但是,這只能解決那些固定不變的列表界面,而目前大部分的APP界面都是動(dòng)態(tài)的,如系統(tǒng)的搜索無線局域網(wǎng)的界面,如下圖:

系統(tǒng)的
無線局域網(wǎng)搜索界面就是一個(gè)典型的動(dòng)態(tài)cell與靜態(tài)cell混合界面,上面的展示搜索到的WiFI熱點(diǎn)列表是動(dòng)態(tài)的,而下面的配置界面又是靜態(tài)的,如何來快速的開發(fā)這種界面呢?下面就給大家詳細(xì)說來。
效果圖(不多說咱先看看效果圖)

第一步(完成靜態(tài)的部分)
根據(jù)自己的業(yè)務(wù)需求先把靜態(tài)部分用storyboard拖拽完成,如果是在UITableViewController中就直接將TableView設(shè)置為靜態(tài),然后直接拖拽。如果是在UIViewController中請(qǐng)參照之前的文章在ViewController中使用靜態(tài)TableView
拖拽好后,記得預(yù)留好動(dòng)態(tài)cell的位置,如下圖:
重點(diǎn):動(dòng)態(tài)的cell所在的Section中一定要留一個(gè)cell(無論什么cell)否則會(huì)造成崩潰

第二步(代碼部分)
定義一個(gè)枚舉,用于區(qū)分自己的section類型

數(shù)據(jù)源以及代理,動(dòng)態(tài)cell和正常的tableview一樣處理,靜態(tài)的cell直接返回父類就好
//cell的個(gè)數(shù)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if(SectionTypeHobby == section){//愛好 (動(dòng)態(tài)cell)
return self.hobbysArr.count;
}
return [super tableView:tableView numberOfRowsInSection:section];
}
//cell 也可以用注冊(cè)的方式來復(fù)用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if(SectionTypeHobby == indexPath.section){//愛好 (動(dòng)態(tài)cell)
HobbyCell *cell = [tableView dequeueReusableCellWithIdentifier:HobbyCellID];
if(!cell){
cell = [[NSBundle mainBundle] loadNibNamed:HobbyCellID owner:nil options:nil].lastObject;
}
return cell;
}
return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
//cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if(SectionTypeHobby == indexPath.section){//愛好 (動(dòng)態(tài)cell)
return HobbyCellHeight;
}
return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
//cell的縮進(jìn)級(jí)別,動(dòng)態(tài)靜態(tài)cell必須重寫,否則會(huì)造成崩潰
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{
if(SectionTypeHobby == indexPath.section){//愛好 (動(dòng)態(tài)cell)
return [super tableView:tableView indentationLevelForRowAtIndexPath: [NSIndexPath indexPathForRow:0 inSection:SectionTypeHobby]];
}
return [super tableView:tableView indentationLevelForRowAtIndexPath:indexPath];
}
這樣靜態(tài)cell與動(dòng)態(tài)cell混用就完成了,當(dāng)然這里我只是隨便舉個(gè)例子,大家可以根據(jù)自己的業(yè)務(wù)需求隨意的搭配動(dòng)態(tài)與靜態(tài)cell混用了。
ps:本人踩過的坑
--- 1.storyboard中動(dòng)態(tài)cell所在的section中必須預(yù)留一個(gè)cell(隨便什么cell)否則會(huì)造成崩潰。
--- 2.- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath;方法必須重寫,否則會(huì)造成崩潰。
最后附上demo地址:Demo
https://github.com/ywdonga/TableViewDynamicStaticCell
給不給星無所謂,大家開心就好。????????
本人在外包公司,以上用法已經(jīng)在N個(gè)項(xiàng)目中使用,目前未出現(xiàn)過任何問題,如果哪位同學(xué)有遇到問題可以聯(lián)系我:QQ 329720990 郵箱 dongyouweie@126.com