Swift - UIButton 改变宽度

Posted

技术标签:

【中文标题】Swift - UIButton 改变宽度【英文标题】:Swift - UIButton changes width 【发布时间】:2019-12-14 18:28:24 【问题描述】:

我遇到了一个问题,UIButton 正在更改it's width if I add anotherbuttoninside the sameview`。

这是没有第二个button的样子:

如果我将第二个按钮(标题:“愿望清单?”)限制在同一个 view 内,这就是它的外观:

这就是我创建圆形图像按钮的方式:

let wishButton: UIButton = 
    let v = UIButton()
    v.setBackgroundImage(UIImage(named: "wishButton"), for: .normal)
    v.translatesAutoresizingMaskIntoConstraints = false
    v.addTarget(self, action: #selector(wishButtonTapped), for: .touchUpInside)
    v.contentVerticalAlignment = .fill
    v.contentHorizontalAlignment = .fill
    return v
()

// constrain wishButton
    wishButton.centerXAnchor.constraint(equalTo: popUpView.centerXAnchor).isActive = true
    wishButton.centerYAnchor.constraint(equalTo: popUpView.centerYAnchor, constant: 70).isActive = true
    wishButton.heightAnchor.constraint(equalToConstant: 72).isActive = true
    wishButton.widthAnchor.constraint(equalToConstant: 72).isActive = true

第二个带有标题的按钮:

let dropDownButton: dropDownBtn = 
    let v = dropDownBtn()
    v.setTitle("Wishlist?", for: .normal)
    v.translatesAutoresizingMaskIntoConstraints = false
    return v
()

        // constrain dropDownButton
    dropDownButton.centerXAnchor.constraint(equalTo: popUpView.centerXAnchor).isActive = true
    dropDownButton.centerYAnchor.constraint(equalTo: popUpView.centerYAnchor).isActive = true
    wishButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
    wishButton.widthAnchor.constraint(equalToConstant: 40).isActive = true

【问题讨论】:

IDK 你如何将它们 X 和 Y 居中并给出这样的外观 【参考方案1】:

你们有冲突

wishButton.heightAnchor.constraint(equalToConstant: 72).isActive = true
wishButton.widthAnchor.constraint(equalToConstant: 72).isActive = true

wishButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
wishButton.widthAnchor.constraint(equalToConstant: 40).isActive = true

你的意思可能是

dropDownButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
dropDownButton.widthAnchor.constraint(equalToConstant: 40).isActive = true

【讨论】:

以上是关于Swift - UIButton 改变宽度的主要内容,如果未能解决你的问题,请参考以下文章

单击 UIButton 以显示 UIPickerView 并在按钮标题上选择 ID:Swift

类型“UIButton”没有成员“发件人”

Swift:在 UIButton 类中设置宽度和高度

stackView swift中uibutton问题的自动布局/宽度

如何在 Swift 中以编程方式调整 UIButton 中文本的字体大小以适应宽度?

swift 设置UIbutton图片文字位置布局