请教各位是如何根据 UILabel 字数的长度来自动更新多种 UITableViewCell 情况下 cell 的高度 ?

2015-04-22 17:07:45 +08:00
 SeanChense
比如现在有两种 cell 需要自动计算高度来容纳 UILabel,大家是怎么做的呢?
有没有什么比较流行的做法?比如根据一行能容纳多少字算有多少行来更新高度,不知道这个是不是很常见。
4243 次点击
所在节点    iDev
24 条回复
expkzb
2015-04-22 17:41:28 +08:00
holy_sin
2015-04-22 17:46:08 +08:00
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension

>= ios7
holy_sin
2015-04-22 17:46:51 +08:00
可能需要autolayout,这个不敢确定
Knights
2015-04-22 18:44:44 +08:00
NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
CGRect rect = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGFloat height = MAX(rect.size.height, 95.0);

return height;
SeanChense
2015-04-22 18:46:57 +08:00
@Knights 没看懂 囧
Knights
2015-04-22 18:52:42 +08:00
@SeanChense 在cell里直接用autolayout是更省事的办法。我的这个是根据text字符串的长度、字体计算出cell的高度,width是屏幕的宽度。
SeanChense
2015-04-22 18:53:22 +08:00
@Knights 从一楼给出的链接来看,AutoLayout 一点都不省事
Knights
2015-04-22 18:56:31 +08:00
@SeanChense 很省事啊,xib里直接拖
SeanChense
2015-04-22 22:07:05 +08:00
@Knights 我是用 Masonry 手写的约束
l12ab
2015-04-22 22:25:23 +08:00
我的都是纯代码,加载cell前计算label高度,然后算出cell高度,存到数组里。这种做法应该不可取
SeanChense
2015-04-22 22:28:04 +08:00
@l12ab 那大家标准的做法是怎么做的?
1# 给出的做法感觉复杂好多好多
babyname
2015-04-22 22:36:50 +08:00
ios7直接autolayout
max0ne
2015-04-22 23:03:20 +08:00
有一种很土的方法是用 [UILabel cellThatFits:CGRectMake(width , MAX_FLOAT)].height 得到label的高度
SeanChense
2015-04-22 23:13:32 +08:00
@babyname 我对 AutoLayout 操作无能,总是不生效,内容挤成一团
kukat
2015-04-22 23:57:19 +08:00
终极方案 http://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights/18746930#18746930

另外,不要因为不会用AutoLayout而否定他,做动态布局特别是动态Cell高度的时候AutoLayout还是很好用的,多看看文档多读读代码很快就能上手的。
icodesign
2015-04-23 00:00:39 +08:00
一楼给出的回答中 iOS8 是标准做法,你可以 Masonry + AutoLayout 写在 cell 里面, iOS7 的实现的话反正是要算的,至于怎么算就各显神通吧。。还是 IOS8方便。- -!
expkzb
2015-04-23 09:26:29 +08:00
不用autolayout坑会很多,在所有项目中我都用PureLayout(以前叫 UIView+Autolayout)

如果觉得那套自适应的流程麻烦,现在有https://github.com/forkingdog/UITableView-FDTemplateLayoutCell

重点是,UILabel要设定 preferredMaxLayoutWidth ,这样才能算出高度
expkzb
2015-04-23 09:29:48 +08:00
如果只支持iOS8以上就不用那么麻烦了,写完约束,定一个 estimatedRowHeight 就可以了
lawder
2015-04-24 13:23:43 +08:00
@expkzb 如果我的tableView是跟屏幕一样宽的,UILabel设定 preferredMaxLayoutWidth时也根据屏幕宽度来设置吗?
expkzb
2015-04-24 21:26:23 +08:00
@lawder 如果你的label和两边有间距,那就是 屏幕宽度 - 间距

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/185522

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX