iOS开发精进技术重塑iOS开发

iOS tableview静态cell动态cell混用

2017-05-09  本文已影响4131人  门前有棵葡萄树

前言

在之前的文章中有写过,如何在ViewController中使用静态TableView 这样我们可以在任何一个界面中嵌套一个静态的tableView,大大的提高了界面的开发效率。
但是,这只能解决那些固定不变的列表界面,而目前大部分的APP界面都是动态的,如系统的搜索无线局域网的界面,如下图:

Paste_Image.png
系统的无线局域网搜索界面就是一个典型的动态cell与静态cell混合界面,上面的展示搜索到的WiFI热点列表是动态的,而下面的配置界面又是静态的,如何来快速的开发这种界面呢?下面就给大家详细说来。

效果图(不多说咱先看看效果图)

tableview.gif

第一步(完成静态的部分)

根据自己的业务需求先把静态部分用storyboard拖拽完成,如果是在UITableViewController中就直接将TableView设置为静态,然后直接拖拽。如果是在UIViewController中请参照之前的文章在ViewController中使用静态TableView
拖拽好后,记得预留好动态cell的位置,如下图:
重点:动态的cell所在的Section中一定要留一个cell(无论什么cell)否则会造成崩溃

Paste_Image.png

第二步(代码部分)

定义一个枚举,用于区分自己的section类型

Paste_Image.png

数据源以及代理,动态cell和正常的tableview一样处理,静态的cell直接返回父类就好

//cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(SectionTypeHobby == section){//爱好 (动态cell)
        return self.hobbysArr.count;
    }
    return [super tableView:tableView numberOfRowsInSection:section];
}
//cell 也可以用注册的方式来复用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(SectionTypeHobby == indexPath.section){//爱好 (动态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){//爱好 (动态cell)
        return HobbyCellHeight;
    }
    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}
//cell的缩进级别,动态静态cell必须重写,否则会造成崩溃
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(SectionTypeHobby == indexPath.section){//爱好 (动态cell)
        return [super tableView:tableView indentationLevelForRowAtIndexPath: [NSIndexPath indexPathForRow:0 inSection:SectionTypeHobby]];
    }
    return [super tableView:tableView indentationLevelForRowAtIndexPath:indexPath];
}

这样静态cell与动态cell混用就完成了,当然这里我只是随便举个例子,大家可以根据自己的业务需求随意的搭配动态与静态cell混用了。
ps:本人踩过的坑
--- 1.storyboard中动态cell所在的section中必须预留一个cell(随便什么cell)否则会造成崩溃。
--- 2.- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath;方法必须重写,否则会造成崩溃。
最后附上demo地址:Demo
https://github.com/ywdonga/TableViewDynamicStaticCell
给不给星无所谓,大家开心就好。😊😊😊😊
本人在外包公司,以上用法已经在N个项目中使用,目前未出现过任何问题,如果哪位同学有遇到问题可以联系我:QQ 329720990 邮箱 dongyouweie@126.com

上一篇 下一篇

猜你喜欢

热点阅读