首页 > 解决方案 > Swift - UIButton 以编程方式设置约束

问题描述

我在设置我的heightwidth constraints为我的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

这是它目前的样子:

在此处输入图像描述

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

标签: iosswiftuibuttonconstraints

解决方案


我注意到的一件事是您似乎没有设置按钮的框架

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

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

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


推荐阅读