[英]Autolayout for UIButton in table view cell not working
你必須實現你自己的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.