设为首页 加入收藏

TOP

iOS之处理不等高TableViewCell的几种方法(一)
2017-10-13 10:24:08 】 浏览:8558
Tags:iOS 处理 等高 TableViewCell 方法

课题一:如何计算Cell高度

方案一:直接法(面向对象)

直接法,就是把数据布局到Cell上,然后拿到Cell最底部控件的MaxY值。

第一步:创建Cell并正确设置约束,使文字区域高度能够根据文字内容多少自动调整

QQ截图20160329114325.png

添加好约束

第二步:再给这个Cell添加点别的东东,就叫这个东东BottomCub了。为Cub添加好约束。

QQ截图20160329114358.png

随便添加点什么

第三步:为这个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
 
//  Cell的构造方法
+ (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;
}
 
/**
  *  拿到bottomCub的最大Y值并返回
  */
- (CGFloat)cellHeight
{
     //  强制布局之前,需要先手动设置下cell的真实宽度,以便于准确计算
     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;
 
/** 测试数据 - Cell中文字内容数组*/
@property(copy,nonatomic) NSArray *testTitleArray;
 
@end
 
@implementation AskCellViewController
 
- (void)viewDidLoad {
     [ super  viewDidLoad];
     [self.view addSubview:self.tableView];
 
     self.tableView.frame = self.vie
首页 上一页 1 2 3 4 5 下一页 尾页 1/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇《2015中国移动应用性能管理白皮.. 下一篇performSelector withObject afte..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目