[英]Autolayout aspect ratio constraints
I want to set a subview constraint as follows. 我想如下设置一个子视图约束。 If the interface is landscape (view.bounds.width > view.bounds.height),set aspect ratio of subview to be 4:3.
如果界面为横向(view.bounds.width> view.bounds.height),则将子视图的高宽比设置为4:3。 In portrait mode, it should be 3:4.
在纵向模式下,应为3:4。 While I can always change the constraints programmatically on auto rotation, wondering if there is a clever way of designing constraints that is only one time.
虽然我总是可以通过编程方式在自动旋转上更改约束,但想知道是否只有一种聪明的设计约束的方法。
You'll have to listen for the UIDevice.orientationDidChangeNotification
notification like in this example: 您必须像下面的示例一样监听
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])
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.