如何在表视图中的UITableViewCells中使用“自动布局”,让每个单元格的内容和子视图确定行高度(自身/自动),同时保持平滑的滚动性能?
当前回答
我只是对rowHeight和estimatedRowHeight的两个值进行了一些愚蠢的尝试和错误,并认为它可能会提供一些调试细节:
如果同时设置它们,或者仅设置估计的RowHeight,则将获得所需的行为:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 1.00001 // MUST be greater than 1
建议您尽最大努力得到正确的估计,但最终结果并无不同。这只会影响你的表现。
如果只设置rowHeight,即只执行以下操作:
tableView.rowHeight = UITableViewAutomaticDimension
您的最终结果不会如预期:
如果将estimatedRowHeight设置为1或更小,则无论rowHeight如何,都会崩溃。
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 1
我崩溃了,出现以下错误消息:
Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'table view row height
must not be negative - provided height for index path (<NSIndexPath:
0xc000000000000016> {length = 2, path = 0 - 0}) is -1.000000'
...some other lines...
libc++abi.dylib: terminating with uncaught exception of type
NSException
其他回答
可变高度UITableViewCell的快速示例
为Swift 3更新
胡威廉(William Hu)的快速回答很好,但在我第一次学习做某事时,它能帮助我掌握一些简单而详细的步骤。下面的示例是我在学习使用可变单元格高度制作UITableView时的测试项目。我基于Swift的这个基本UITableView示例。
完成的项目应如下所示:
创建新项目
它可以只是一个单视图应用程序。
添加代码
将新的Swift文件添加到项目中。将其命名为MyCustomCell。此类将保存添加到情节提要中单元格的视图的出口。在这个基本示例中,每个单元格中只有一个标签。
import UIKit
class MyCustomCell: UITableViewCell {
@IBOutlet weak var myCellLabel: UILabel!
}
我们稍后将连接此插座。
打开ViewController.swift并确保您具有以下内容:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// These strings will be the data for the table view cells
let animals: [String] = [
"Ten horses: horse horse horse horse horse horse horse horse horse horse ",
"Three cows: cow, cow, cow",
"One camel: camel",
"Ninety-nine sheep: sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep baaaa sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep",
"Thirty goats: goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat "]
// Don't forget to enter this in IB also
let cellReuseIdentifier = "cell"
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// delegate and data source
tableView.delegate = self
tableView.dataSource = self
// Along with auto layout, these are the keys for enabling variable cell height
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
cell.myCellLabel.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
重要说明:
以下两行代码(以及自动布局)使可变单元格高度成为可能:tableView.estimatedRowHeight=44.0tableView.rowHeight=UITableViewAutomaticDimension
设置情节提要
将表视图添加到视图控制器中,并使用自动布局将其固定到四边。然后将表视图单元格拖到表视图上。然后将标签拖到原型单元格上。使用自动布局将标签固定到表视图单元的内容视图的四个边缘。
重要说明:
自动布局与我上面提到的两行重要代码一起工作。如果不使用自动布局,它将无法工作。
其他IB设置
自定义类名和标识符
选择TableViewCell并将自定义类设置为MyCustomCell(我们添加的Swift文件中的类名称)。还将Identifier设置为cell(与上面代码中用于cellReuseIdentifier的字符串相同)。
标签的零行
将标签中的行数设置为0。这意味着多行,并允许标签根据其内容调整自身大小。
连接插座
控件从情节提要中的表视图拖动到ViewController代码中的tableView变量。对Prototype单元格中的Label和MyCustomCell类中的myCellLabel变量执行同样的操作。
完成了
您现在应该能够运行项目并获得高度可变的单元格。
笔记
此示例仅适用于iOS 8及更高版本。如果您仍然需要支持iOS 7,那么这将不适用于您。未来项目中您自己的自定义单元格可能不止一个标签。确保将所有内容固定正确,以便自动布局可以确定要使用的正确高度。你可能还需要使用垂直抗压和拥抱。有关这方面的更多信息,请参阅本文。如果不固定前缘和后缘(左侧和右侧),则可能还需要设置标签的preferredMaxLayoutWidth,以便它知道何时换行。例如,如果在上面的项目中向标签添加了“水平居中”约束,而不是固定前缘和后缘,则需要将此行添加到tableView:cellForRowAtIndexPath方法:cell.myCellLabel.referencedMaxLayoutWidth=表格视图边界宽度
另请参见
了解iOS 8中的自调整单元格和动态类型具有不同行高的表视图单元格Swift的UITableView示例
动态表视图单元格高度和自动布局
解决故事板自动布局问题的好方法:
- (CGFloat)heightForImageCellAtIndexPath:(NSIndexPath *)indexPath {
static RWImageCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [self.tableView dequeueReusableCellWithIdentifier:RWImageCellIdentifier];
});
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height;
}
要设置行高和估计行高的自动尺寸,请确保以下步骤对单元格/行高布局有效。
分配和实现表视图数据源和委托将UITableViewAutomaticDimension分配给rowHeight和estimatedRowHeight实现委托/dataSource方法(即heightForRowAt并向其返回值UITableViewAutomaticDimension)
-
目标C:
// in ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
@property IBOutlet UITableView * table;
@end
// in ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.table.dataSource = self;
self.table.delegate = self;
self.table.rowHeight = UITableViewAutomaticDimension;
self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
斯威夫特:
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Don't forget to set dataSource and delegate for table
table.dataSource = self
table.delegate = self
// Set automatic dimensions for row height
// Swift 4.2 onwards
table.rowHeight = UITableView.automaticDimension
table.estimatedRowHeight = UITableView.automaticDimension
// Swift 4.1 and below
table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = UITableViewAutomaticDimension
}
// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Swift 4.2 onwards
return UITableView.automaticDimension
// Swift 4.1 and below
return UITableViewAutomaticDimension
}
对于UITableviewCell中的标签实例
设置行数=0(换行模式=截断尾部(&L)设置与其超级视图/单元格容器相关的所有约束(顶部、底部、左右)。可选:如果您希望标签覆盖最小垂直区域,即使没有数据,也可以设置标签的最小高度。
注意:如果您有多个标签(UIElements)具有动态长度,应根据其内容大小进行调整:请调整要以更高优先级展开/压缩的标签的“内容拥抱和抗压优先级”。
在我的例子中,填充是因为sectionHeader和sectionFooter的高度,故事板允许我将其更改为最小值1。因此,在viewDidLoad方法中:
tableView.sectionHeaderHeight = 0
tableView.sectionFooterHeight = 0
我只是对rowHeight和estimatedRowHeight的两个值进行了一些愚蠢的尝试和错误,并认为它可能会提供一些调试细节:
如果同时设置它们,或者仅设置估计的RowHeight,则将获得所需的行为:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 1.00001 // MUST be greater than 1
建议您尽最大努力得到正确的估计,但最终结果并无不同。这只会影响你的表现。
如果只设置rowHeight,即只执行以下操作:
tableView.rowHeight = UITableViewAutomaticDimension
您的最终结果不会如预期:
如果将estimatedRowHeight设置为1或更小,则无论rowHeight如何,都会崩溃。
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 1
我崩溃了,出现以下错误消息:
Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'table view row height
must not be negative - provided height for index path (<NSIndexPath:
0xc000000000000016> {length = 2, path = 0 - 0}) is -1.000000'
...some other lines...
libc++abi.dylib: terminating with uncaught exception of type
NSException
推荐文章
- 如何使用Xcode创建。ipa文件?
- 动态改变UILabel的字体大小
- 在iPhone上确定用户是否启用了推送通知
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 错误ITMS-9000:“冗余二进制文件上传。火车1.0版本已经有一个二进制版本上传。
- Swift -转换为绝对值
- 从父iOS访问容器视图控制器
- 自定义dealloc和ARC (Objective-C)
- 调整UITableView的大小以适应内容
- 在代码中为UIButton设置一个图像
- NSRange从Swift Range?
- UICollectionView中的单元格间距
- 我如何在我的iOS应用程序中每n分钟得到一个后台位置更新?
- 如何使用iOS创建GUID/UUID
- 禁用所呈现视图控制器的交互式撤销