答案 0 :(得分:1)
您必须实现自己的UIButton
子类,以提供您想要的内容。您可以使用以下TitleAdaptingButton
实现,它会覆盖intrinsicContentSize
以适应标题标签中的文字,即使在垂直轴上也是如此:
class TitleAdaptingButton: UIButton {
override var bounds: CGRect {
didSet {
if !oldValue.equalTo(bounds) {
invalidateIntrinsicContentSize()
}
}
}
override var intrinsicContentSize: CGSize {
get {
let labelSize = titleLabel!.sizeThatFits(CGSize(width: frame.width - (titleEdgeInsets.left + titleEdgeInsets.right), height: .greatestFiniteMagnitude))
let desiredButtonSize = CGSize(width: labelSize.width + contentEdgeInsets.left + contentEdgeInsets.right, height: labelSize.height + contentEdgeInsets.top + contentEdgeInsets.bottom)
return desiredButtonSize
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.titleLabel?.numberOfLines = 0
// if you want the text centered
// self.titleLabel?.textAlignment = .center
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.titleLabel?.numberOfLines = 0
// if you want the text centered
// self.titleLabel?.textAlignment = .center
}
}
将此类添加到项目中后,只需将其设置为每个按钮的自定义类:
但请记住,要使按钮适应,必须允许单元格定义自己的大小,因此您必须在tableView
上使用以下内容:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44 // or your better estimation