使用 UITableViewAutomaticDimension 显示多行标签的自定义单元格
Custom cell to display multiline label using UITableViewAutomaticDimension
目标:
- 使用自动布局和
UITableViewAutomaticDimension
在 UITableView
中的自定义单元格上显示多行标签。
- 单元格应根据每个
UILabel
中的文本而有所不同。
我做了什么:
- 使用自动布局
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
label.numberOfLines = 0
(标签是我新建的标签)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
- 已将
UILabel
添加到 contentView
- 将
UILabel
中的约束添加到内容视图
问题:
- 当我使用自定义单元格时,一些文本被剪裁 (...)
- 有时滚动不是很流畅
尝试与 UITableViewCell
相同:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
textLabel.numberOfLines = 0
(textLabel
已经存在于 UITableViewCell
中)
- 滚动看起来很流畅
- 没有裁剪,文本显示正确
- 打印了
cell.textLabel?.preferredMaxLayoutWidth
并显示 0
问题:
- 为什么它在
UITableViewCell
而不是我的自定义单元格上工作正常?
- 在这两种情况下,
preferredMaxLayoutWidth
都没有被设置。
- 请让我知道我缺少什么。
我的自定义单元格的代码:
class MultilineLabelCell : UITableViewCell {
let label = UILabel()
//MARK: Initializers
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
//MARK: Setup Views
func setup() {
setupLabel()
setupLayout()
}
func setupLabel() {
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.numberOfLines = 0
contentView.addSubview(label)
}
func setupLayout() {
let views = ["label" : label]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|",
options: .allZeros,
metrics: nil,
views: views)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]-|",
options: .allZeros,
metrics: nil,
views: views)
contentView.addConstraints(horizontalConstraints)
contentView.addConstraints(verticalConstraints)
}
}
查看控制器代码
override func loadView() {
super.loadView()
tableView.registerClass(MultilineLabelCell.self, forCellReuseIdentifier: ViewController.cellIdentifier)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
}
func populateData() {
dataArray.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat")
dataArray.append("Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum")
dataArray.append("Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam,")
dataArray.append("nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?")
dataArray.append("But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?")
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(ViewController.cellIdentifier) as! MultilineLabelCell
cell.label.numberOfLines = 0
cell.label.text = dataArray[indexPath.row]
return cell
}
虽然在 UITableViewCell
的内容视图中以编程方式 views/controls 给出约束并希望根据您的文本长度获得动态单元格大小,但您需要从所有四个方面明确给出填充(提供一些值).按照以下进行更改。看起来像一个错误
在setupLayout方法中
func setupLayout() {
let views = ["label" : label]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-5-[label]-5-|",
options: .allZeros,
metrics: nil,
views: views)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-5-[label]-5-|",
options: .allZeros,
metrics: nil,
views: views)
contentView.addConstraints(horizontalConstraints)
contentView.addConstraints(verticalConstraints)
}
目标:
- 使用自动布局和
UITableViewAutomaticDimension
在UITableView
中的自定义单元格上显示多行标签。 - 单元格应根据每个
UILabel
中的文本而有所不同。
我做了什么:
- 使用自动布局
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
label.numberOfLines = 0
(标签是我新建的标签)label.setTranslatesAutoresizingMaskIntoConstraints(false)
- 已将
UILabel
添加到contentView
- 将
UILabel
中的约束添加到内容视图
问题:
- 当我使用自定义单元格时,一些文本被剪裁 (...)
- 有时滚动不是很流畅
尝试与 UITableViewCell
相同:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
textLabel.numberOfLines = 0
(textLabel
已经存在于UITableViewCell
中)- 滚动看起来很流畅
- 没有裁剪,文本显示正确
- 打印了
cell.textLabel?.preferredMaxLayoutWidth
并显示 0
问题:
- 为什么它在
UITableViewCell
而不是我的自定义单元格上工作正常? - 在这两种情况下,
preferredMaxLayoutWidth
都没有被设置。 - 请让我知道我缺少什么。
我的自定义单元格的代码:
class MultilineLabelCell : UITableViewCell {
let label = UILabel()
//MARK: Initializers
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
//MARK: Setup Views
func setup() {
setupLabel()
setupLayout()
}
func setupLabel() {
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.numberOfLines = 0
contentView.addSubview(label)
}
func setupLayout() {
let views = ["label" : label]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|",
options: .allZeros,
metrics: nil,
views: views)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]-|",
options: .allZeros,
metrics: nil,
views: views)
contentView.addConstraints(horizontalConstraints)
contentView.addConstraints(verticalConstraints)
}
}
查看控制器代码
override func loadView() {
super.loadView()
tableView.registerClass(MultilineLabelCell.self, forCellReuseIdentifier: ViewController.cellIdentifier)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
}
func populateData() {
dataArray.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat")
dataArray.append("Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum")
dataArray.append("Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam,")
dataArray.append("nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?")
dataArray.append("But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?")
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(ViewController.cellIdentifier) as! MultilineLabelCell
cell.label.numberOfLines = 0
cell.label.text = dataArray[indexPath.row]
return cell
}
虽然在 UITableViewCell
的内容视图中以编程方式 views/controls 给出约束并希望根据您的文本长度获得动态单元格大小,但您需要从所有四个方面明确给出填充(提供一些值).按照以下进行更改。看起来像一个错误
在setupLayout方法中
func setupLayout() {
let views = ["label" : label]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-5-[label]-5-|",
options: .allZeros,
metrics: nil,
views: views)
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-5-[label]-5-|",
options: .allZeros,
metrics: nil,
views: views)
contentView.addConstraints(horizontalConstraints)
contentView.addConstraints(verticalConstraints)
}