UIButton高度和自动布局

时间:2019-08-02 08:01:38

标签: ios swift autolayout

在我的一个ViewController中,我使用的UIView底部有两个按钮。显然,我要适合屏幕上的两个按钮,所以我在用:

leftButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -16).isActive = true
rightButton.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -16).isActive = true
//16 points between the buttons
leftButton.rightAnchor.constraint(equalTo: rightButton.leftAnchor, constant: -16).isActive = true 
//right alignment for the buttons
rightButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -16).isActive = true 
//left padding for the left button - 16 points
leftButton.leftAnchor.constraint(greaterThanOrEqualTo: self.leftAnchor, constant: 16).isActive = true 

//rightButton can't be less wide than 1/3 of its superview
rightButton.widthAnchor.constraint(greaterThanOrEqualToConstant: widthOfTheView / 3).isActive = true

它可以工作,但是如果我的左键标题很长怎么办?我的左按钮的高度变大了,没关系。但是我的右键仍然不是很高,而且看起来有点难看。

right button is too small

好的,但是如果我告诉自动布局,我希望右按钮的高度与左按钮的高度相同。

rightButton.heightAnchor.constraint(equalTo: leftButton.heightAnchor, constant: 0).isActive = true

我认为这将是一个解决方案,但我得到的却是这个:

left button too small

从技术上讲,它们的高度相等,但这不是我想要的结果。

我以为,问题可能出在按钮内的UIEdgeInsets中,但事实并非如此(我杀了这一行,结果是相同的。)

我想我不能在两个按钮之间选择最大高度并将其用作约束常量,因为在此阶段它们各自的帧为零。

我试图将另一个UIView用作这两个按钮的容器,但结果是相同的。

我可以通过关闭“自动布局”并计算按钮的大小和框架来解决此问题,但是我现在暂时不想这样做。

那么,我在这里做什么错了?

3 个答案:

答案 0 :(得分:2)

使用UIStackView进行设置非常容易

.axis = .horizontal
.alignment = .fill
.distribution = .fillEqually
.spacing = 12

enter image description here

根据尺寸变化自动调整:

enter image description here

代码如下:

class MultilineRoundedButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    func commonInit() -> Void {
        self.titleLabel?.numberOfLines = 0
        self.titleLabel?.textAlignment = .center
        self.setContentHuggingPriority(UILayoutPriority.defaultLow + 1, for: .vertical)
        self.setContentHuggingPriority(UILayoutPriority.defaultLow + 1, for: .horizontal)
        self.layer.cornerRadius = 8
    }

    override var intrinsicContentSize: CGSize {
        let size = self.titleLabel!.intrinsicContentSize
        return CGSize(width: size.width + contentEdgeInsets.left + contentEdgeInsets.right, height: size.height + contentEdgeInsets.top + contentEdgeInsets.bottom)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        titleLabel?.preferredMaxLayoutWidth = self.titleLabel!.frame.size.width
    }
}

class TwoButtonsView: UIView {

    let theStackView: UIStackView = {
        let v = UIStackView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.axis = .horizontal
        v.alignment = .fill
        v.distribution = .fillEqually
        v.spacing = 16
        return v
    }()

    let leftButton: MultilineRoundedButton = {
        let v = MultilineRoundedButton()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.setTitle("Really (really!) long first button title", for: .normal)
        v.backgroundColor = UIColor(red: 184.0 / 255.0, green: 233.0 / 255.0, blue: 133.0 / 255.0, alpha: 1.0)
        return v
    }()

    let rightButton: MultilineRoundedButton = {
        let v = MultilineRoundedButton()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.setTitle("Second title", for: .normal)
        v.backgroundColor = UIColor(red:  74.0 / 255.0, green: 143.0 / 255.0, blue: 226.0 / 255.0, alpha: 1.0)
        return v
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() -> Void {

        leftButton.titleLabel?.font = UIFont.systemFont(ofSize: 24.0, weight: .bold)
        rightButton.titleLabel?.font = leftButton.titleLabel?.font

        addSubview(theStackView)
        theStackView.addArrangedSubview(leftButton)
        theStackView.addArrangedSubview(rightButton)

        NSLayoutConstraint.activate([
            theStackView.topAnchor.constraint(equalTo: topAnchor),
            theStackView.bottomAnchor.constraint(equalTo: bottomAnchor),
            theStackView.leadingAnchor.constraint(equalTo: leadingAnchor),
            theStackView.trailingAnchor.constraint(equalTo: trailingAnchor),
            ])

    }

}

class TwoButtonViewController: UIViewController {

    let buttonsView: TwoButtonsView = {
        let v = TwoButtonsView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(buttonsView)

        NSLayoutConstraint.activate([
            buttonsView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20.0),
            buttonsView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20.0),
            buttonsView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20.0),
            ])
    }

}

答案 1 :(得分:1)

此答案是@ DonMag答案的延续,如果您希望方便的扩展根据其内部文本调整UIButton的大小,请使用以下代码:-

extension UIButton {
func wrapContentHeight(constantValue : CGFloat) -> CGFloat {
    self.titleLabel?.text = self.title(for: .normal)

    self.titleLabel?.numberOfLines = 0
    self.titleLabel?.frame.size.width = self.frame.width
    self.titleLabel?.lineBreakMode = .byWordWrapping
    self.superview?.layoutIfNeeded()

    let height = self.titleEdgeInsets.top + self.titleEdgeInsets.bottom + (self.titleLabel?.frame.height ?? 45)
    if height < constantValue {return constantValue}
    return height
}

,您可以将上述扩展应用于按钮的高度约束,如下所示:-

btnHeight.constant = selectionBtn.wrapContentHeight(constantValue: 45)

答案 2 :(得分:-1)

在行下更改

leftButton.rightAnchor.constraint(equalTo: rightButton.leftAnchor, constant: -16).isActive = true

收件人

leftButton.rightAnchor.constraint(greaterThanOrEqualTo: rightButton.leftAnchor, constant: -16).isActive = true

您可以设置

rightButton.heightAnchor.constraint(equalTo: leftButton.heightAnchor).isActive = true

当前,leftButton的右锚点正尝试填充-16常量,并且由于该左键正使用GreaterOrEqual拉伸,这会增加按钮之间的距离,但尺寸会很好。