Have UITableViewCell resize itself with autolayout(让 UITableViewCell 使用自动布局调整自身大小)
问题描述
我在 UITableViewCell
中有 3 个标签,并设置了标签以便它们自动换行.如果他们自动换行,则文本将进入下一个单元格.如何让 AutoLayout 根据内容展开单元格,而无需在 heightForRowAtIndex
方法中编写代码?难道没有一个约束我可以用来根据 contentView 自动调整单元格吗?
I have 3 labels in a UITableViewCell
and have the labels set so they will wordwrap. If they word wrap the text goes into the next cell. How do I get AutoLayout to expand the cell based on the content without having to write code in the heightForRowAtIndex
method? Isn't there a constraint I can use to automatically adjust the cell based on the contentView?
如果文本不包含在标签中,则单元格看起来很好.一旦包裹起来,就是问题发生的时候,我想让单元格调整大小以适应内容,并且底部标签和底部之间的间距与顶部和顶部标签之间的间距相同.
The cell looks fine if the text doesn't wrap in the label. Once it wraps that is when the problem occurs and I would like to have the cell resize to fit the content and have the same spacing between the bottom label and the bottom as there is between the top and top label.
推荐答案
很遗憾,您不能这样做.表格视图首先计算自己的总高度,并且在加载时对每个单元格的大小有一个固定的概念,它不会从外向内确定它的高度,也不会让布局约束改变单元格的高度.
Unfortunately no, you can't do this. A table view calculates its own total height first and has a fixed idea of the size of each cell as they load, it won't determine it's height from the outside in and it won't let layout constraints change the height of a cell.
如果您考虑表格是如何工作的,以及单元格重用,那么如果不加载每个单元格并将其添加到滚动视图,并对整个事物执行布局传递,您就无法真正根据其单元格调整表格大小.这可能会导致性能很差.
If you think about how tables work, with cell reuse, then you couldn't really size the table from its cells without loading in every cell and adding it to the scrollview, and performing a layout pass on the whole thing. That would probably lead to quite poor performance.
您可以尝试填充空闲"单元格(即您刚刚实例化的单元格,未添加到表中)并在计算 heightForRow 时为数据源中的每一行布置它.
You could experiment with populating a "free" cell (i.e a cell you've just instantiated, not added to a table) and laying it out for each row in your datasource when calculating heightForRow.
这篇关于让 UITableViewCell 使用自动布局调整自身大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:让 UITableViewCell 使用自动布局调整自身大小
基础教程推荐
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01