如何使用Swift中的SnapKit制作宽度和高度相等的UIView?

时间:2016-10-26 08:50:00

标签: ios swift autolayout snapkit

我想在Swift中使用SnapKit创建一个UIView矩形,就像这样

lazy var customView: UIView = {
        let view = UIView(frame: CGRect())
        self.addSubview(view)
        view.snp.makeConstraints({ (make) in
            make.left.top.bottom.equalToSuperview().inset(self.inset)
            make.width.equalTo(make.height)  // Error in this line
        })
        return view
    }()

3 个答案:

答案 0 :(得分:6)

您必须使用view.snp.height代替make.height

lazy var customView: UIView = {
    let view = UIView(frame: CGRect())
    self.addSubview(view)
    view.snp.makeConstraints({ (make) in
        make.left.top.bottom.equalToSuperview().inset(self.inset)
        make.width.equalTo(view.snp.height) // <---
    })
    return view
}()

答案 1 :(得分:2)

如果您在同一个超级视图中有2个视图,则可以执行下一个操作:

    view1.snp.makeConstraints { (make) in
        make.leading.equalToSuperview()
        make.bottom.equalToSuperview()
        make.top.equalToSuperview()
    }

    view2.snp.makeConstraints { (make) in
        make.trailing.equalToSuperview()
        make.bottom.equalToSuperview()
        make.top.equalToSuperview()
        make.leading.equalTo(view1.snp.trailing)
        make.width.equalTo(view1.snp.width)
    }

和结果

enter image description here

以同样的方式,使用view.snp.widthview.snp.height您可以使用 SnapKit

设置视图的相等性

答案 2 :(得分:0)

    view.snp.makeConstraints({ (make) in
        make.left.top.bottom.equalToSuperview().inset(self.inset)
        make.width.equalTo(view.snp.height) 
    })