gpt4 book ai didi

ios - 自动布局宽高比限制

转载 作者:行者123 更新时间:2023-11-29 05:28:11 24 4
gpt4 key购买 nike

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

最佳答案

您必须监听 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])
}
}

关于ios - 自动布局宽高比限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57942471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com