【问题标题】:Using SnapKit to Aspect Ratio and less size使用 SnapKit 长宽比和更小的尺寸
【发布时间】:2023-03-25 09:24:01
【问题描述】:

我正在尝试在 SnapKit 中创建此布局的约束,但我很难设置最大尺寸 (lessThanOrEqual)。

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

【问题讨论】:

  • SnapKit 确实有 .lessThanOrEqualTo(...).greaterThanOrEqualTo(...) 方法......也许如果你描述一下你想要做什么?
  • @DonMag 我需要我的视图来保持 435:600 的纵横比和不超过这个比例的大小。也就是说,在 iPhone 上,尺寸会比定义的要小,而在 iPad 上,尺寸正是这样。我能够使用 XIB 创建此行为,但通过 SnapKit 代码我不能。

标签: swift ios-autolayout snapkit


【解决方案1】:

如果我明白你的目的,应该这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多