如何在iOS Swift中以编程方式创建自动布局等宽约束?

18
如何以编程方式为多个视图提供等宽和等高的约束。我查看了谷歌,但没有找到通过自动布局使等宽和等高的约束的完美答案。 我的代码如下所示:
  var countNoOfViews:Int = 3   
 @IBOutlet var viewForRow1: UIView!

override func viewDidLoad() {
        super.viewDidLoad()
 self.specialButtonViewLeft()
}

func specialButtonViewLeft(){

    for i in 0..<countNoOfViews{
        var customView:UIView!
        customView = UIView(frame: CGRect.zero)
        customView.translatesAutoresizingMaskIntoConstraints = false
        viewForRow1.addSubview(customView)

        let widthConstraint = NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal,toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20.0)

        let topConstraint = NSLayoutConstraint(item: customView, attribute: .top, relatedBy: .equal,toItem: self.viewForRow1, attribute: .top, multiplier: 1.0, constant: 0)

        let bottomConstraint = NSLayoutConstraint(item: customView, attribute: .bottom, relatedBy: .equal,toItem: self.viewForRow1, attribute: .bottom, multiplier: 1.0, constant: 0)

        let leadingConstraint = NSLayoutConstraint(item: customView, attribute: .leading, relatedBy: .equal, toItem: self.viewForRow1, attribute: .leading, multiplier: 1, constant: customLeadingSpaceLeft)

        customLeadingSpaceLeft = customLeadingSpaceLeft + customViewWidth

        arrayLeftBtnConstraints.append(widthConstraint)

        if i == 0{
            customView.backgroundColor = UIColor.red
        }else if i == 1{
            customView.backgroundColor = UIColor.green
        }else if i == 2{
            leftViewVal = customLeadingSpaceLeft
            customView.backgroundColor = UIColor.black
        }
        customView.alpha = 0.50
        viewForRow1.addConstraints([widthConstraint, leadingConstraint,topConstraint,bottomConstraint])
    }
}

我想以编程方式添加等宽约束。


你能完成工作了吗? - Bista
2个回答

36

您可以有三种方法来实现这个:

1)使用 anchors(锚点):

view.widthAnchor.constraint(equalTo: otherView.widthAnchor, multiplier: 1.0).isActive = true

2)可视化格式:

简单的例子 - "H:|[otherView]-[view(==otherView)]|"

3)“老派”的约束:

NSLayoutConstraint(item: #view, attribute: .width, relatedBy: .equal, toItem: #otherView, attribute: .width, multiplier: 1.0, constant: 0.0).isActive = true

希望对某些人有所帮助。


10
更简洁的写法:view.widthAnchor == otherView.widthAnchor,并使其生效:isActive = true - JaredH

8

试试这个:

let widthConstraint = NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal, toItem: viewForRow1, attribute: .width, multiplier: 0.25, constant: 0.0)

multiplier: 0.25表示customView的宽度将是父视图viewForRow1的四分之一。


谢谢。但我有多个视图将等宽分割到超级视图中。另外一件事是,我想根据方向改变程序自动布局约束的宽度,例如纵向 - 30和横向 - 40宽度。 - Chirag Patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接