Swift-UIButton以编程方式设置约束

问题描述 投票:0回答:1

我在为height设置widthconstraints UIButton时遇到问题。我不知道为什么这段代码不起作用:

let wishButton: UIButton = {
    let v = UIButton()
    v.setImage(UIImage(named: "wishButton"), for: .normal)
    v.translatesAutoresizingMaskIntoConstraints = false
    v.addTarget(self, action: #selector(wishButtonTapped), for: .touchUpInside)
    return v
}()

这些是我的约束:

wishButton.centerXAnchor.constraint(equalTo: popUpView.centerXAnchor).isActive = true
wishButton.centerYAnchor.constraint(equalTo: popUpView.centerYAnchor, constant: 150).isActive = true
wishButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
wishButton.widthAnchor.constraint(equalToConstant: 100).isActive = true

此刻是这样:

enter image description here

这很奇怪,因为其他两个constraints正常工作。可能只是一个愚蠢的错误,但是我很新,也很感谢每一个帮助:)

ios swift uibutton constraints
1个回答
0
投票

我注意到的一件事是它看起来不像您设置了按钮的frame

初始化按钮后尝试添加此行:

v.frame = CGRect(x: 0, y: 0, width: 100, height: 100)

我不确定是否需要它,但是如果您的按钮根本不显示,则可能会解决此问题


0
投票

将其添加到您的UIButton初始化中,它将起作用

let wishButton: UIButton = {
    let v = UIButton()
    v.setImage(UIImage(named: "wishButton"), for: .normal)
    v.translatesAutoresizingMaskIntoConstraints = false
    v.contentVerticalAlignment = .fill
    v.contentHorizontalAlignment = .fill
    v.addTarget(self, action: #selector(wishButtonTapped), for: .touchUpInside)
    return v
}()
© www.soinside.com 2019 - 2024. All rights reserved.