基于 UILabel 文本量的 UITableViewCell 自动高度 [英] UITableViewCell auto height based on amount of UILabel text
问题描述
我在我的故事板中设置了一些棘手的设置,我有一个包含 UITableViewController 的 UIViewController.在 UITableViewController 中,我有几个原型单元,我已经链接到代码中的子类 uitableviewcell 对象.
I have a bit of a tricky set up in my storyboard, I have a UIViewController that holds a UITableViewController. Within the UITableViewController I have several prototypecells I have linked to subclassed uitableviewcell objects in code.
使用约束和故事板,我想根据 UILabel 最终的大小来更改原型单元格的高度,而这取决于进入其中的文本.
Using constraints and storyboard I would like to change the height of my prototype cell depending on the size the UILabel ends up being which is dependant on the text going into it.
目前我有一个
UIViewController
-- UITableViewController
-- -- UITableViewCell ((melchat) prototype cell)
-- -- -- ContentView
-- -- -- -- UIView ((background) view with drop shadow card type effect)
-- -- -- -- -- UIImageView (Avatar)
-- -- -- -- -- IUlabel (dynamic (depending on code/input) multi line UILabel)
我希望 UILabel 如何调整 UIView(背景)的大小,然后反过来影响 UITableViewCell 的高度.
Some how I would like the UILabel to resize the UIView (background) then in turn effect the height of that UITableViewCell.
我使用的是 XCode 8.2.1
I am using XCode 8.2.1
我在情节提要中截取了布局并应用了约束.
I have taken a screen shot of the layout in storyboard and constraints applied.
我已将约束更新为几乎所有返回到 ContentView 并将 uilabel 行数更新为 0,然后还实现了 UITableViewAutomaticDimension 代码,但它仍然无法正常工作.请参阅下面的代码和屏幕截图.
I have updated my constraints to pretty much all go back to ContentView and have updated uilabel line count to 0 and then also implemented the UITableViewAutomaticDimension code but its still not working. Please see code and screen shots below.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
推荐答案
在 Dao 的回答上更进一步..
To go a little further on Dao's answer..
他说得对,你需要使用UITableViewAutomaticDimension
此外,您需要确保以一种将单元格中的所有内容约束到单元格 contentView 的方式设置约束.因此您的标签可能需要诸如
Also, you need to ensure that you setup your constraints in a way that all of the content in the cell is constrained to the cells contentView. So your label will likely need constraints such as
- 导致 ImageView 的约束
- 对 contentView 的顶部约束
- 对 contentView 的底部约束
- 对 contentView 的尾随约束
确保将 UILabel 设置为多行(或行 = 0)并且它应该可以工作.
Make sure that you set the UILabel to multiline (or lines = 0) and it should work.
如果您使用的是 heightForRowAt 委托函数,请确保您返回 UITableViewAutomaticDimension
If you are using the heightForRowAt delegate functions ensure you return UITableViewAutomaticDimension
这篇关于基于 UILabel 文本量的 UITableViewCell 自动高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!