1、cell中嵌套Tableview
实现思路
笔者尝试画了一张图,尽量反映出实现的思路:
外层UITableView通过HYBMasonryAutoCellHeight计算cell的高度并缓存起来,而cell中所嵌套的UITableView(显示评论信息的表格)也是通过HYBMasonryAutoCellHeight来计算cell的高度并缓存。当评论TableView增加或者删除一条数据时,通过代理反馈到外层TableView,然后重装计算行高并更新缓存。
数据建模
这里使用了两个模型类HYBTestModel是外层UITableView的数据源模型,而HYBCommentModel是评论UITableView的数据源模型。
HYBTestModel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@interface
HYBTestModel
: NSObject
@property
(
nonatomic
,
copy
)
NSString
*uid
;
@property
(
nonatomic
,
copy
)
NSString
*title
;
@property
(
nonatomic
,
copy
)
NSString
*desc
;
@property
(
nonatomic
,
copy
)
NSString
*headImage
;
// 评论数据源
@property
(
nonatomic
,
strong
)
NSMutableArray
*commentModels
;
// 因为评论是动态的,因此要标识是否要更新缓存
@property
(
nonatomic
,
assign
)
BOOL
shouldUpdateCache
;
@end
|
其中,uid必须保证唯一,它是用来缓存高度的唯一标识符,通常model的id作为uniqueKey。增加shouldUpdateCache属性的目的是在增加或者删除评论时,以识别是否需要重新计算行高并刷新对应的缓存高度。
HYBCommentModel
1
2
3
4
5
6
7
8
9
10
|
@interface
HYBCommentModel
: NSObject
@property
(
nonatomic
,
copy
)
NSString
*cid
;
@property
(
nonatomic
,
copy
)
NSString
*name
;
@property
(
nonatomic
,
copy
)
NSString
*reply
;
@property
(
nonatomic
,
copy
)
NSString
*comment
;
@end
|
这里的cid是指评论id,它是作为缓存行高的key。
外层HYBTestCell
这个是外层UITableView所需要使用的cell,它里面会嵌套着评论的UITableView。当评论内容发生变化时,通过代理来实现数据的刷新,行高的重新计算与缓存。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@class
HYBTestModel
;
@protocol
HYBTestCellDelegate
<NSObject>
-
(
void
)
reloadCellHeightForModel
:
(
HYBTestModel
*
)
model
atIndexPath
:
(
NSIndexPath
*
)
indexPath
;
@end
@interface
HYBTestCell
: UITableViewCell
@property
(
nonatomic
,
weak
)
id
delegate
;
-
(
void
)
configCellWithModel
:
(
HYBTestModel
*
)
model
indexPath
:
(
NSIndexPath
*
)
indexPath
;
@end
|
当我们配置其数据时,我们要计算出评论的tablview的高度。这里是通过HYBMasonryAutoCellHeight这个开源库来实现的。当配置数据时,通过遍历所有的评论模型,然后计算cell的行高,累加起来就是Tablview的高度,然后刷新tableview的约束。这样就可以正常地计算出整个外部cell的高度了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
-
(
void
)
configCellWithModel
:
(
HYBTestModel
|