//UIViewController的willRotate父类方法使用
//以前工作中没有遇到这个需求,所以一直没了解这个父类的方法,用到后其实很简单
//在你的项目中可能会遇到翻转设备使其竖屏出现新的view,横屏对应的view都Hide
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation,duration: TimeInterval) {
print("willRotate 旋转了")
if toInterfaceOrientation.isLandscape{
print("isLandscape")
for v in self.view.subviews{
if v.tag == 10{
v.removeFromSuperview()
}else{
v.isHidden = false
}
}
}else if toInterfaceOrientation.isPortrait {
print("isPortrait")
for v in self.view.subviews{
v.isHidden = true
}
UIView.animate(withDuration: duration, animations: {
let v = UIView()
v.tag = 10
v.frame = CGRect(x: 10, y: 10, width: UIScreen.main.bounds.width - 20, height: UIScreen.main.bounds.height - 20)
self.view.addSubview(v)
v.backgroundColor = UIColor.blue
})
}
}
----就这样实现了横竖屏view的切换,在多嘴一句:
if UIDevice.current.orientation.isPortrait{
print("UIDevice.current.orientation.isPortrait 鸡鸡--------")
} else {
print("UIDevice.current.orientation.isLandscape 鸡鸡-----")
}
可判断横竖屏