我在为height
设置width
和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
正常工作。可能只是一个愚蠢的错误,但是我很新,也很感谢每一个帮助:)
我注意到的一件事是它看起来不像您设置了按钮的frame。
初始化按钮后尝试添加此行:
v.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
我不确定是否需要它,但是如果您的按钮根本不显示,则可能会解决此问题
将其添加到您的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
}()