美文网首页iOS碎碎念
iOS关于横屏的有关问题

iOS关于横屏的有关问题

作者: tiGress | 来源:发表于2016-11-14 11:31 被阅读450次

上周四用了半天的时间,项目中写的有关视频横屏的问题都没有实现。查了很多资料,都没有解决。今天早上终于解决了。记录下改问题。

有关横屏的设置

- (IBAction)large:(id)sender{

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];

[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

}

横屏返回

- (IBAction)largeBack:(id)sender{

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];

[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

}

设置

这些都是系统的方法,设置了这些方法后,横屏一直不展示。当当当。。。。解决问题的办法来了。

因为在这个地方设置的是强制竖屏,所以,横屏的方法是不会走的。所以要在APPdelegate中做一下设置。

1.首先在 appDelegate.h 中创建一个 BOOL 属性,

@property (nonatomic,assign)BOOL allowRotation; //是否支持横屏

2.然后到 appDelegate.m 中实现:

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{

if (self.allowRotation) {

return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait ;

}

return UIInterfaceOrientationMaskPortrait;

}

这样,当 allowRotation 为 YES 时,就支持横屏了。

3、需要支持的页面中,修改 allowRotation 的值为 YES,即可支持横竖屏旋转了:

- (void)viewWillAppear:(BOOL)animated{

[super viewWillAppear:animated];

// 出现时可旋转

((AppDelegate *)[UIApplication sharedApplication].delegate).allowRotation = YES;

}

4.记得在页面将要消失时修改为只支持竖屏:

- (void)viewWillDisappear:(BOOL)animated {

[super viewWillDisappear:animated];

// 消失时恢复竖屏

((AppDelegate *)[UIApplication sharedApplication].delegate).allowRotation = NO;

// 立即变为竖屏

[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];

5. 上述代码实现的是自动旋转、如果需要强制旋转的的话,在上述把横屏打开的前提下,使用下面的代码即可进行强制的横屏或者竖屏了:

// 竖屏

[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];

// 横屏

[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];

相关文章

网友评论

  • 武一顶顶:看了好几篇都没看懂,只有这篇通俗易懂👍
  • 4382a8550a04:为什么都设置了之后 [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"]; 执行横屏无效呢 没反应
    OnlyLoveYu:- (void)viewWillAppear:(BOOL)animated
    {
    [super viewWillAppear:animated];
    ((AppDelegate *)[UIApplication sharedApplication].delegate).allowRotation = YES;
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
    }
    - (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];
    ((AppDelegate *)[UIApplication sharedApplication].delegate).allowRotation = NO;
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
    }
    直接上代码吧,你之前肯定是把这行代码写在viewDidLoad里面了

本文标题:iOS关于横屏的有关问题

本文链接:https://www.haomeiwen.com/subject/tudhpttx.html