我正在尝试使用自动布局来调整 UITableViewCell 的大小以始终适合其内容。
每个单元格包含两个标签topLabel
和bottomLabel
,它们是垂直堆叠的。我希望两个标签都换行并显示它们的所有文本。
我正在使用 iOS8。
这是我的代码
class MyTableViewCell: UITableViewCell {
@IBOutlet var topLabel: UILabel!
@IBOutlet var bottomLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
topLabel = UILabel()
topLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
topLabel.numberOfLines = 0
contentView.addSubview(topLabel)
bottomLabel = UILabel()
bottomLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
bottomLabel.numberOfLines = 0
contentView.addSubview(bottomLabel)
let viewDictionary = ["topLabel": topLabel, "bottomLabel": bottomLabel]
var constraints = [NSLayoutConstraint]()
contentView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[topLabel]-|",
options:NSLayoutFormatOptions(0),
metrics: nil,
views: viewDictionary))
contentView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-[bottomLabel]-|",
options:NSLayoutFormatOptions(0),
metrics: nil,
views: viewDictionary))
contentView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-[topLabel]-[bottomLabel]-|",
options:NSLayoutFormatOptions(0),
metrics: nil,
views: viewDictionary))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class MyTableViewController: UITableViewController, UITableViewDataSource {
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return 5;
}
override func viewDidLoad() {
tableView.rowHeight = UITableViewAutomaticDimension
super.viewDidLoad()
}
override func tableView(
tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell {
let cell = MyTableViewCell(
style: UITableViewCellStyle.Default,
reuseIdentifier: nil)
cell.topLabel.text = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26"
cell.bottomLabel.text = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
return cell
}
}
但是,只有顶部标签的文本换行。结果是
我不确定我是否弄乱了我的约束,或者我是否应该设置另一个属性,或者这是不可能的。任何帮助将不胜感激。
最佳答案
在您的 cellForRowAtIndexPath
中添加这一行似乎可以解决问题。
cell.layoutIfNeeded()
关于ios - 带有两个 UILabel 的自动调整 UITableViewCell 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28164460/