swift - 使用 SnapKit 到纵横比和更小的尺寸

标签 swift ios-autolayout snapkit

我正在尝试在 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()
}

最佳答案

如果我明白你要做什么,应该这样做:

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

关于swift - 使用 SnapKit 到纵横比和更小的尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57894335/

相关文章:

ios - 在 UILabel 的特定字符后面画圈

ios - 在 Swift 中显示 UITextField 的底部边框不适用于约束。

ios - Snapkit 和 UILabel 的轮换

ios - 如何添加约束以将 tableview 固定到其父底部

swift - 从 firebase 数据库查询数据时的奇怪行为

ios - 如何在 SpriteKit 中模拟一个比屏幕还大的世界?

ios - 当使用手势关闭呈现的 View Controller 时如何获得通知?

ios - 收缩高度约束动画问题

ios - 可变高度 UITableViewCell 在滚动到列表末尾并旋转后展开

ios - 自定义TableViewCell触发NSLayoutConstraint错误 'UIView-Encapsulated-Layout-Height'