【发布时间】:2016-09-03 06:55:25
【问题描述】:
UITableViewCell 的子类包含带有多行文本的UIButton,即属性numberOfLines = 0。
表格视图单元格的高度不同,因此单元格高度设置为UITableViewAutomaticDimension。
当添加带有多个文本行的UILabel 时,单元格高度会调整。但是它不适应UIButton,实际上按钮的框架也不适应其titleLabel的框架。
如何使表格视图单元格及其内容视图适应按钮高度?
class MyButtonCell: UITableViewCell {
var button: UIButton!
var buttonText: String?
convenience init(buttonText: String?) {
self.init()
self.buttonText = buttonText
button = UIButton(type: UIButtonType.System)
button.titleLabel?.numberOfLines = 0
button.titleLabel?.lineBreakMode = .ByWordWrapping
button.contentHorizontalAlignment = .Center
button.titleLabel?.textAlignment = .Center
button.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubView(button)
NSLayoutConstraint.activateConstraints([
button.topAnchor.constraintEqualToAnchor(self.contentView.topAnchor),
button.bottomAnchor.constraintEqualToAnchor(self.contentView.bottomAnchor),
button.rightAnchor.constraintEqualToAnchor(self.contentView.rightAnchor),
button.leftAnchor.constraintEqualToAnchor(self.contentView.leftAnchor)
])
button.setTitle(buttonText, forState: .Normal)
button.setTitleColor(buttonTextColor, forState: UIControlState.Normal)
button.titleLabel?.font = buttonFont
}
}
单元格高度通过以下方式自动计算:
tableView.estimatedRowHeight = 100
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
更新:
https://github.com/mtrezza/ButtonCellHeightBug上的示例项目
已提交 Apple 错误报告 #26170971。
【问题讨论】:
-
你在使用故事板和自动布局吗?
-
-
知道了。设置文本后,在按钮上尝试 sizeToFit()。
-
@Siriss 试过没有成功:-/
-
您是在使原型单元出队,还是为每个 indexPath 创建一个新单元?
标签: ios swift uitableview uibutton