Search code examples
iosswiftsnapkit

How to use aspect ratio constraint in iOS using SnapKit?


I trying to create an aspect ratio constraint 1:1 using snapkit. If I would using storyboard, that could simply be achieved using the aspect ratio constraint tool, but with SnapKit, this not appears to be so easy.

How can I achieve that?


Solution

  • You can do it in that way:

    view.snp.makeConstraints { (make) in
        make.width.equalTo(view.snp.height).multipliedBy(1.0 / 1.0)
    }
    

    Using only iOS the following extension works:

    extension UIView {
        func aspectRatio(_ ratio: CGFloat) -> NSLayoutConstraint {
            return NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: self, attribute: .width, multiplier: ratio, constant: 0)
        }
    }