问题描述
如何使用Swift 3检测方向变化?
How to detect orientation change after it happened using Swift 3?
我需要在更改后对其进行检测以计算帧大小.
I need to detect it after change to calculate frame size.
编辑
我问了这个问题,因为我需要像这个问题一样重新绘制方向更改的视图:
I asked this question because I need to redraw view on orientation change like in this question: Can't get background gradient to fill entire screen upon rotation
我不知道如何实现被标记为正确答案的答案.
I don't know how to implement answer that is marked as a correct answer.
我尝试了另一个答案
self.backgroundImageView.layer.sublayers?.first?.frame = self.view.bounds
但是它不起作用.
在viewDidLoad()
我有
let color1 = UIColor(red: 225.0/255.0, green: 210.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor
let color2 = UIColor(red: 255.0/255.0, green: 125.0/255.0, blue: 77.0/255.0, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [ 0.0, 1.0]
gradientLayer.frame = self.view.bounds
self.view.layer.insertSublayer(gradientLayer, at: 0)
推荐答案
上面接受的答案会在过渡之前返回帧大小.因此您的视图不会更新.在过渡完成后,您需要获取帧大小.
The above accepted answer returns frame size before transition.So your view is not updating..You need to get the frame size after the transition has been completed.
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in
let orient = UIApplication.shared.statusBarOrientation
switch orient {
case .portrait:
print("Portrait")
case .landscapeLeft,.landscapeRight :
print("Landscape")
default:
print("Anything But Portrait")
}
}, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
//refresh view once rotation is completed not in will transition as it returns incorrect frame size.Refresh here
})
super.viewWillTransition(to: size, with: coordinator)
}
这篇关于方向更改后,UIView框架未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!