【问题标题】:Autolayout aspect ratio constraints自动布局纵横比约束
【发布时间】:2020-01-16 10:36:50
【问题描述】:

我想设置一个子视图约束如下。如果界面是横向的(view.bounds.width > view.bounds.height),设置子视图的纵横比为 4:3。在纵向模式下,它应该是 3:4。虽然我总是可以在自动旋转时以编程方式更改约束,但想知道是否有一种巧妙的方法来设计只有一次的约束。

【问题讨论】:

  • 在手机上,您可以使用尺寸等级并将约束链接到这些尺寸等级。不幸的是,iPad 在纵向和横向上都有相同的尺寸等级,因此您需要一些代码来根据方向覆盖特征。

标签: ios swift autolayout uikit ios-autolayout


【解决方案1】:

您必须像下面的示例一样收听UIDevice.orientationDidChangeNotification 通知:

class ViewController3: UIViewController {

    let blueSubview: UIView = {
        let view = UIView()
        view.backgroundColor = .blue
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

    var blueSubviewHeight = NSLayoutConstraint()
    var blueSubviewWidth = NSLayoutConstraint()

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(refreshConstraints), name: UIDevice.orientationDidChangeNotification, object: nil)

        refreshConstraints()
        setUI()
    }

    fileprivate func setUI() {
        view.backgroundColor = .white

        view.addSubview(blueSubview)
        [blueSubview.leftAnchor.constraint(equalTo: view.leftAnchor),
        blueSubview.topAnchor.constraint(equalTo: view.topAnchor),
        blueSubviewWidth,
        blueSubviewHeight].forEach({ $0.isActive = true })
    }

    @objc func refreshConstraints() {
        NSLayoutConstraint.deactivate([blueSubviewWidth, blueSubviewHeight])

        if view.frame.width > view.frame.height {
            blueSubviewWidth = blueSubview.widthAnchor.constraint(equalToConstant: view.frame.height * (4/3))
            blueSubviewHeight = blueSubview.heightAnchor.constraint(equalToConstant: view.frame.height)
        }
        else {
            blueSubviewWidth = blueSubview.widthAnchor.constraint(equalToConstant: view.frame.width)
            blueSubviewHeight = blueSubview.heightAnchor.constraint(equalToConstant: view.frame.width * (4/3))
        }

        NSLayoutConstraint.activate([blueSubviewWidth, blueSubviewHeight])
    }
}

【讨论】:

    猜你喜欢
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 2014-10-23
    • 2015-02-28
    • 2015-03-22
    • 1970-01-01
    • 2015-05-28
    相关资源
    最近更新 更多