课题一:如何计算Cell高度
方案一:直接法(面向对象)
直接法,就是把数据布局到Cell上,然后拿到Cell最底部控件的MaxY值。
第一步:创建Cell并正确设置约束,使文字区域高度能够根据文字内容多少自动调整
添加好约束
第二步:再给这个Cell添加点别的东东,就叫这个东东BottomCub了。为Cub添加好约束。
随便添加点什么
第三步:为这个Cell写一个返回Cell高度 - 也就是BottomCub最大Y值的方法
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
31
32
33
34
|
#import "TestCell.h"
@interface TestCell ()
@property (strong, nonatomic) IBOutlet UILabel *longLabel;
@property (strong, nonatomic) IBOutlet UIView *bottomCub;
@end
@implementation TestCell
+ (instancetype)creatWithTitle :(NSString *)title inTableView :(UITableView *)tableView
{
TestCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(self)];
if
(!cell) {
cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:kNilOptions].lastObject;
}
cell.longLabel.text = title;
return
cell;
}
- (CGFloat)cellHeight
{
CGRect rect = self.frame;
rect.size.width = [[UIScreen mainScreen] bounds].size.width;
self.frame = rect;
[self layoutIfNeeded];
return
CGRectGetMaxY(self.bottomCub.frame);
}
@end
|
第四步:在代理方法中设置Cell高度
*注意:计算Cell高度的过程,一定不要放在heightForRow代理方法中!这一点在后文中将会有所提及。
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
#import "AskCellViewController.h"
#import "TestCell.h"
@interface AskCellViewController ()
@property (strong, nonatomic) UITableView *tableView;
@property(copy,nonatomic) NSArray *testTitleArray;
@end
@implementation AskCellViewController
- (void)viewDidLoad {
[
super
viewDidLoad];
[self.view addSubview:self.tableView];
self.tableView.frame = self.vie |