iOS 11下iPad横屏模式UIImagePickerController状态栏异常问题求助
解决iOS 11 iPad横屏UIImagePickerController状态栏竖屏异常问题
我之前在做iPad横屏项目时正好踩过iOS 11这个蛋疼的状态栏坑,给你几个亲测有效的解决思路:
方法1:自定义UIImagePickerController子类强制状态栏方向
iOS 11的相册二级页面会忽略popover的方向设置,我们可以通过子类重写状态栏相关方法,强制它跟随当前设备的横屏状态:
class FixedOrientationImagePicker: UIImagePickerController { // 强制状态栏跟随当前系统方向 override var preferredStatusBarOrientation: UIInterfaceOrientation { return UIApplication.shared.statusBarOrientation } // 限制仅支持横屏方向 override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .landscapeLeft.union(.landscapeRight) } }
之后用这个子类代替原生的UIImagePickerController初始化即可,比如:
let picker = FixedOrientationImagePicker() picker.sourceType = .photoLibrary picker.modalPresentationStyle = .popover // 设置popover的锚点(比如触发按钮的frame) picker.popoverPresentationController?.sourceView = yourTriggerButton picker.popoverPresentationController?.sourceRect = yourTriggerButton.bounds present(picker, animated: true)
方法2:通过AppDelegate全局控制方向
如果子类方案不生效,你可以在AppDelegate里针对图片选择器的场景单独设置支持的方向:
首先给UIViewController加一个获取顶层控制器的扩展,方便判断当前页面:
extension UIViewController { func topMostViewController() -> UIViewController { if let presentedVC = presentedViewController { return presentedVC.topMostViewController() } return self } }
然后在AppDelegate里实现方向控制方法:
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { guard let topVC = window?.rootViewController?.topMostViewController() else { return .allButUpsideDown // 替换成你的App默认支持的方向 } // 判断当前是否处于图片选择器相关页面 if topVC is UIImagePickerController || topVC.parent is UIImagePickerController { // 强制返回横屏方向 return .landscapeLeft.union(.landscapeRight) } return .allButUpsideDown }
额外注意事项
- 确保你的
Info.plist中已经勾选了Landscape Left和Landscape Right这两个横屏方向,否则系统会默认限制竖屏。 - 如果旋转设备后状态栏仍未恢复,可以手动触发刷新:
UIApplication.shared.setStatusBarOrientation(UIApplication.shared.statusBarOrientation, animated: true)
内容的提问来源于stack exchange,提问作者szemian
相关产品推荐
相关产品推荐

