在View中监听屏幕的旋转
- 第一种方法,我们在view的生命周期的layoutSubviews方法中监听statusBarOrientation,达到监听屏幕的横竖屏状态
- (void)layoutSubviews{[self _shouldRotateToOrientation:(UIDeviceOrientation)[UIApplication sharedApplication].statusBarOrientation];
//这里推荐使用状态栏判断}-(void)_shouldRotateToOrientation:(UIDeviceOrientation)orientation {
if (orientation == UIDeviceOrientationPortrait ||orientation ==
UIDeviceOrientationPortraitUpsideDown) { // 竖屏} else { // 横屏}
}
- 第二种方法,使用通知监听屏幕的横竖屏状态
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
- (void)orientChange:(NSNotification *)notification{
UIInterfaceOrientation interfaceOritation = [[UIApplication sharedApplication] statusBarOrientation];
/*
statusBarOrientation4种状态:
UIInterfaceOrientationUnknown= UIDeviceOrientationUnknown,
UIInterfaceOrientationPortrait= UIDeviceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft= UIDeviceOrientationLandscapeRight,
UIInterfaceOrientationLandscapeRight= UIDeviceOrientationLandscapeLeft*/
}
- 第三种在控制器中如果想手动控制屏幕的旋转,如视频播放的横竖屏旋转,我们可以用以下方法来实现,使用这种方法要把
这里的控制横竖屏的勾都取消掉
文章图片
Snip20170916_4.png
class AppDelegate: UIApplicationDelegate{//添加一个控制屏幕旋转的属性
var allowRotation : Bool = false///横竖屏解决方案
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if allowRotation == true {
return .all
}else{
return .portrait
}
}
}//在其他要旋转的控制器中只需要设置allowRotation的值就可以了// 用appdelegate来控制设备的旋转
let appdelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.allowRotation = true// MARK:-----屏幕旋转---------------
override var shouldAutorotate: Bool {
return true
}override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if player.isLocked {
return .landscape
} else {
return .all
}
}