动态表格视图单元格

3
我希望创建动态表格单元格视图,可以根据标签中的文本对齐元素。单元格高度随标签中的文本而异。设计这种类型的设计的最佳方法是什么。 如何在表视图单元格中获得与标签文本完全对齐的准确对齐方式,其中其他元素在水平方向上居中对齐,我不想截断尾巴,我想要完整的文本。

if the text is in two lines sample.

提前致谢。


您可以创建与左标签相同高度的正确标签。然后尝试将文本对齐到中间。为此,您可以创建自定义标签,使文本在中间对齐。 - Sandeep Ahuja
2个回答

0

关于对齐:

您可以创建与左标签相同高度的右标签。 然后尝试将文本居中对齐。为此,您可以子类化UILabel类并将文本矩形对齐方式更改为中间。

For Dynamic Height:
 1. Use auto layout when creating your table view cells.
 2. Set the table view rowHeight to equal UITableViewAutomaticDimension.
 3. Set the estimatedRowHeight or implement the height estimation delegate method.

    Pro Tip: the trick to getting auto layout to work on a UITableViewCell is to ensure you have constraints to pin each subview on all sides — that is, each subview should have leading, top, trailing and bottom constraints.
    Furthermore, you need a clear line of constraints going from the top to the bottom of the contentView. This ensures that auto layout correctly determines the height of the contentView based on its subviews.
    The tricky part is that Interface Builder often won’t warn you if you’re missing some of these constraints; auto layout simply doesn’t return the correct heights when you run the project. For example, it may return 0 for the cell height, which is a clue that your constraints need more work.
    If you run into issues when working with your own projects, try adjusting your constraints until the above criteria are met.


For Detail, please refer to original source of above text is https://www.raywenderlich.com/87975/dynamic-table-view-cell-height-ios-8-swift

0
首先,在你的 viewDidLoad 中,你可以设置例如:
tableView.estimatedRowHeight = 160
tableView.rowHeight = UITableViewAutomaticDimension

然后,在绘制xib单元格时,您可以遵循此模式:

+-view----------------+
|       |             |
|    -label-          |
|       |             | 
| +-subview--------+  |
| |      |   |     |  | 
|-| -label-label-  |--|
| |      |   |     |  | 
| |   -label-      |  | 
| |      |         |  |
| +----------------+  |
|        |            |
|     -label-         |
|        |            | 
+---------------------+

每个标签都设置了顶部、底部、前导和后续约束。 如果您需要压缩标签组,可以添加子视图将它们包含在内。


感谢Alessandro Ornano的回复和解决方案。有没有办法使用在iOS 9中引入的堆栈视图? - niks290192
当然,我认为堆栈视图是未来的方向。例如,我喜欢这里的介绍 http://www.appcoda.com/stack-views-intro/ ,但如果您想制作一个 iOS 8.x 兼容的应用,则无法像官方指南 https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIStackView_Class_Reference/ 中所解释的那样使用它们。 - Alessandro Ornano
感谢提供宝贵信息。您能否为我提供一些关于自动布局和约束的链接,以便更容易地理解它们的机制和方法。 - niks290192
你可以看一下这个指南:https://www.raywenderlich.com/115440/auto-layout-tutorial-in-ios-9-part-1-getting-started-2,它非常快速和清晰。P.S. 如果您认为这个答案是正确的,请选择为此页面的正确答案,谢谢。 - Alessandro Ornano

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接