首页 > 解决方案 > UIButton 高度和自动布局

问题描述

在我的一个 ViewControllers 中,我使用 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

它有效,但如果我的左按钮标题很长怎么办?我的左键变高了,没关系。但是我的右键仍然不是很高,看起来略显丑陋。

右键太小

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

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

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

左键太小

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

我认为,也许问题出在按钮内的 UIEdgeInsets 中,但事实并非如此(我杀了这条线,结果是一样的)。

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

我尝试使用另一个 UIView 作为这两个按钮的容器,但结果是一样的。

我当然可以通过关闭自动布局并计算按钮大小和框架来解决这个问题,但我现在不想这样做。

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

标签: iosswiftautolayout

解决方案


这个答案是@ 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)

推荐阅读