iOS可折叠的tableView的简单实现

移动开发 iOS
漫漫编程路,刚接触iOS编程的你做好准备了么。凡事从无到有,由简至繁,需要努力和坚韧,那么从最简单的积累开始吧。

这里所说的 tableView 折叠,是借助 insert (insertRowsAtIndexPaths:withRowAnimation:) 和 delete (deleteRowsAtIndexPaths:withRowAnimation:) 对tableView 的 section 进行折叠,效果简单。

我是初学者,还请各位看官指教。

搞这个东西,断断续续了几天,现在终于可以告一段落了,虽然离可重用还有距离,但是我想以经不远了。

遇到的几个问题:

1.NSMutableDictionary

NSMutableDictionary 内的顺序并不是执行 setObjectForKey 的顺序,顺序是乱的(目测是乱的,不知道是不是有什么规律,请指教)。

我在这个东西上绕了一个大圈子。后来在 AppCode  下面调试,才发现这个问题。为保持插入顺序,不得不换成两个 NSMutableArray ,一个存 Key,一个存 Value.

2.headerViewForSection

我想在 numberOfRowsInSection 方法内获取该 section 的 header View ,然后读取自定义的数据,比如当前状态是否是折叠等。

查了一下API,发现有个 headerViewForSection 方法,但是无论如何,它的值一直都是nil,搞不明白。stackoverflow 上有说须要在使用之前用 tableView 的 registerNib:forHeaderFooterViewReuseIdentifier:  或 registerClass:forHeaderFooterViewReuseIdentifier:  方 法,我试了,没用。

3.insertRowsAtIndexPaths 和 deleteRowsAtIndexPaths 同 numberOfRowsInSection 的关系

如果不处理好这个关系,大概所有的问题都是这样的:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 6. The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (9), plus or minus the number of rows inserted or deleted from that section (0 inserted, 3 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete row 2 from section 4 which only contains 0 rows before the update'

大楖是说,numberOfRowsInSection 返回的数字和 insert / delete 后,section 所包含的行数不一致。

在 tableView 的 endUpdates 方法之前,应该对标志变量做处理。endUpdates 后,会重新刷新 tableView ,numberOfRowsInSection 会重新被调用。

不理想的地方(坏代码)

同上面讲的1和2 ,由于 NSMutableDictionary 的无顺序,我将 MutableDictionary 换成了 MutableArray 。

由于无法获取指定 section 的 headerView ,所以,我只能将以经生成的 headerView 记录到某个 MutableArray 内,以供使用。

用 xib 设计自定义的 UIView

在新建 Objective-C Class 的时候,只有基类是 UIViewController 的,才能选“With XIB for user interface” 这个选项。

如果我想自定义一个 UIView , 这个 view 内的控件很多,想想就是一件可怕的事情。还好,可以单独新建一个 xib 文件。

a, 拖一个UIView 到 xib 编辑器中,然后更发这个 view 的size 为 Freeform, 这个 view 就可以自由的改变大小了。

b,更改 class 为自定义的 UIView 

c, File's Owner 的 class 还是 NSObject ,不要改。

d, 如何使用这个自定义的 UIView ?

***,上个效果图吧

责任编辑:闫佳明 来源: cnblogs
相关推荐

2018-04-26 10:43:28

2019-03-20 14:26:56

苹果折叠屏iPhone X Fo

2021-12-01 17:42:42

微信macOS腾讯

2022-03-02 09:53:51

微软FlutterEngine PR

2015-12-29 10:20:40

谷歌眼镜企业

2019-03-15 16:18:41

谷歌可折叠手机

2022-12-29 08:16:46

2019-10-12 17:19:12

WindowsWindows 7Windows 10

2019-05-08 15:21:30

谷歌折叠屏智能手机

2021-08-15 22:58:43

手机折叠手机三星

2022-07-12 06:05:27

NutUI折叠面板组件开发

2012-05-17 12:38:43

iOS

2014-03-12 10:19:54

iOS对象

2013-07-05 10:26:40

Android
点赞
收藏

51CTO技术栈公众号