如何使用 Swift 3 检测方向变化?
我需要在更改后检测它以计算帧大小。
EDIT
我问这个问题是因为我需要重新绘制方向变化的视图,就像这个问题一样:旋转时无法让背景渐变填充整个屏幕 https://stackoverflow.com/questions/20925939/cant-get-background-gradient-to-fill-entire-screen-upon-rotation
我不知道如何实现标记为正确答案的答案。
我尝试了另一个答案
self.backgroundImageView.layer.sublayers?.first?.frame = self.view.bounds
但它不起作用。
In viewDidLoad()
I have
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)
上面接受的答案返回转换前的帧大小。因此您的视图没有更新。您需要在转换完成后获取帧大小。
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)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)