iPad 适配
参考文章: http://www.jianshu.com/p/6ac34ab1ea24
手机旋转状态监听
方法一:
// 状态监听
NotificationCenter.default.addObserver(self, selector: #selector(didOrientate(noti:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
// 处理方法
func didOrientate(noti: NSNotification) {
print("宽 = ", self.view.frame.width)
let orient = UIDevice.current.orientation
switch orient {
case .portrait:
// 正
print("portrait")
break
case .landscapeLeft:
print("landscapeLeft")
break
case .landscapeRight:
print("landscapeRight")
break
case .portraitUpsideDown:
print("portraitUpsideDown")
break
default:
break
}
}
方法二:
/**监听状态
UIApplicationDidChangeStatusBarOrientation
UIApplicationWillChangeStatusBarOrientation
*/
NotificationCenter.default.addObserver(self, selector: #selector(statusBarOrientationChange(noti:)), name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: nil)
// 监听方法处理
func statusBarOrientationChange(noti: NSNotification) {
let orienation = UIApplication.shared.statusBarOrientation
if orienation == .landscapeLeft {
print("左")
}
if orienation == .landscapeRight {
print("右")
}
if orienation == .portrait {
// 正
print("protrait")
}
if orienation == .portraitUpsideDown {
// 倒着
print("down")
}
if orienation == .unknown {
print("unknown")
}
}
方法三:
// 重写父类方法,(貌似转场动画使用该方法)后续研究
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
print("宽1 = ", self.view.frame.width)
print("宽2 = ", size.width)
}
方法四:
// 重写父类监听方法,iOS8 已经弃用
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
print("will 宽 = ", self.view.frame.width)
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
print("did 宽 = ", self.view.frame.width)
print("*************************************")
}
强制横屏:
// AppDelegate中
var changeOrientation: Bool = false
/// 设置横屏/竖屏显示
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if changeOrientation {
return [.landscapeLeft, .portrait, .landscapeRight]
}else {
return .portrait
}
}
/// 被强制横屏的视图
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
(UIApplication.shared.delegate as! AppDelegate).changeOrientation = true
//打开试图的横屏显示
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
(UIApplication.shared.delegate as! AppDelegate).changeOrientation = false
//将试图还原为竖屏
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}