我有一个像这样设置的图像视图:
let buttonImageView: UIImageView = {
let iv = UIImageView()
iv.backgroundColor = .red
iv.translatesAutoresizingMaskIntoConstraints = false
iv.frame.size = CGSize(width: CGFloat(375 * (11 / 59)), height: CGFloat(375 * (11 / 59)))
return iv
}()
然后,我添加约束:
/* center-top button */
// buttonImageView.frame = CGRect(x: 0, y: 0, width: buttonDiameter, height: buttonDiameter)
addConstraint(NSLayoutConstraint(item: buttonImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buttonDiameter))
addConstraint(NSLayoutConstraint(item: buttonImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: buttonDiameter))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[v0]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["v0": buttonImageView]))
// addConstraintsWithFormat("H:[v0]", views: buttonImageView)
addConstraintsWithFormat("V:|-\(buttonSpacing)-[v0]", views: buttonImageView)
//addConstraint(NSLayoutConstraint(item: buttonImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
请忽略"嗨!"广场。它下方的红色方块buttonImageView
应该处于该垂直约束,但水平居中。
答案 0 :(得分:1)
如果以编程方式使用约束,则首先需要激活它们
os.path.join
答案 1 :(得分:0)
替换:
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[v0]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: ["v0": buttonImageView]))
使用:
NSLayoutConstraint(item: buttonImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0).isActive = true
应该做的伎俩。
答案 2 :(得分:-1)
addConstraint(NSLayoutConstraint(item: buttonImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))