我有一个UIButton子类,其高度需要为80pt,但在UIStackView等中使用时宽度表现正常......如何在子类中完成。
以下代码成功更改了高度,但UIStackView不会将布局调整为准确的高度:
class MenuSelectionButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 5.0
}
override func layoutSubviews() {
super.layoutSubviews()
var newFrame = frame
newFrame.size.height = 80
frame = newFrame
}
}
工作代码:
class MenuSelectionButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 5.0
addHeightConstraint()
}
private func addHeightConstraint () {
let heightConstraint = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 80)
NSLayoutConstraint.activateConstraints([heightConstraint])
}
}
答案 0 :(得分:2)
将按钮的高度限制为80并让自动布局处理它。
或者,由于您使用的是UIButton
的自定义子类,因此覆盖instrinsicContentSize
以返回80的高度:
import UIKit
@IBDesignable
class MenuSelectionButton: UIButton {
// Xcode uses this to render the button in the storyboard.
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
// The storyboard loader uses this at runtime.
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override func intrinsicContentSize() -> CGSize {
return CGSize(width: super.intrinsicContentSize().width, height: 80)
}
private func commonInit() {
self.layer.cornerRadius = 5.0
}
}