Using SnapKit to Aspect Ratio and less size
Asked Answered
D

1

8

I am trying to create the constraints of this layout in SnapKit but I have difficulty setting the maximum size (lessThanOrEqual).

layout

let maxWidthContainer: CGFloat = 435
let maxHeightContainer: CGFloat = 600

containerView.snp.makeConstraints {
    $0.width.equalTo(containerView.snp.height).multipliedBy(maxWidthContainer / maxHeightContainer)
    $0.centerX.centerY.equalToSuperview()
    $0.leading.trailing.equalToSuperview().inset(38).priorityLow()
}
Designate answered 11/9, 2019 at 17:46 Comment(2)
SnapKit does have .lessThanOrEqualTo(...) and .greaterThanOrEqualTo(...) methods... Maybe if you describe what you're trying to do?Antilepton
@Antilepton I need my view to keep the aspect ratio of 435: 600 and the size not to exceed this ratio. That is, on an iPhone the size would be smaller than defined, and on the iPad the size would be exactly this. I was able to create this behavior using XIB, but via SnapKit code I can't.Designate
A
21

If I understand what you're going for, this should do it:

    let v = UIView()
    v.backgroundColor = .blue
    view.addSubview(v)

    let maxWidthContainer: CGFloat = 435
    let maxHeightContainer: CGFloat = 600

    v.snp.makeConstraints { (make) in
        // centered X and Y
        make.centerX.centerY.equalToSuperview()

        // at least 38 points "padding" on all 4 sides

        // leading and top >= 38
        make.leading.top.greaterThanOrEqualTo(38)

        // trailing and bottom <= 38
        make.trailing.bottom.lessThanOrEqualTo(38)

        // width ratio to height
        make.width.equalTo(v.snp.height).multipliedBy(maxWidthContainer/maxHeightContainer)

        // width and height equal to superview width and height with high priority (but not required)
        // this will make it as tall and wide as possible, until it violates another constraint
        make.width.height.equalToSuperview().priority(.high)

        // max height
        make.height.lessThanOrEqualTo(maxHeightContainer)
    }
Antilepton answered 11/9, 2019 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.