Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make UIView with equal width and height with SnapKit in Swift?

I want to make a UIView rectangular with SnapKit in Swift, like this

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
    }()
like image 417
Khoren Markosyan Avatar asked Oct 26 '16 08:10

Khoren Markosyan


2 Answers

You have to use view.snp.height instead of 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
}()
like image 138
d.felber Avatar answered Nov 17 '22 12:11

d.felber


If you have 2 view on same superview, you can do next:

    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)
    }

and result

enter image description here

In same manner, using view.snp.width or view.snp.height you can setup equality of views using SnapKit

like image 42
hbk Avatar answered Nov 17 '22 14:11

hbk