【问题标题】:iOS 7 programmatically change UI Orientation effectivelyiOS 7 以编程方式有效地改变 UI 方向
【发布时间】:2014-08-05 14:29:23
【问题描述】:

在通过 stackoverflow 浏览答案后,我决定提出一个问题。

据我了解,我应该重写supportedInterfaceOrientation 来处理方向。例如,为了我这样实现它

- (NSUInteger)supportedInterfaceOrientations {
    if (self.forceLandscape) {
         return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}

这让控制器在出现时以横向模式启动,并在默认情况下启用 forceLandscape。然后有一个按钮可以改变按钮按下的方向

- (IBAction)buttonPress:(id)sender {
    self.forceLandscape = !self.forceLandscape;
    UIInterfaceOrientation o = UIInterfaceOrientationPortrait;
    if (self.forceLandscape) {
       o = UIInterfaceOrientationLandscape;
    }
    [UIApplication sharedApplication].statusBarOrientation = o;
}

按钮按下会在纵向和横向模式之间交替切换。通过设置状态栏方向,它会调用supportedInterfaceOrientations 来改变我的方向。它确实调用该方法并在第一次按下按钮时返回蒙版肖像,但它不会改变我的方向。这是我要解决的问题。希望有解决方法。

将状态栏方向更改替换为此代码

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

调用supportedInterfaceMethod,它确实改变了方向。但是它只能工作一次,并且它可以访问私有代码并且会被 Apple 拒绝,这是不可取的。

【问题讨论】:

    标签: ios objective-c iphone orientation


    【解决方案1】:

    不确定此解决方案是否有效。在我的项目(iOS6,7)中,我固定了方向,所以我不需要强制改变方向。但是,我在 UIViewController 中发现了一个“尝试将设备方向旋转到右侧的函数”

    -(BOOL)shouldAutorotate {
        FLog(@"");
        if (self.forceLandscape) { //force to landscape
            return NO;
        } else {
            return YES; //let's application rotate it self
        }
    }
    -(NSUInteger)supportedInterfaceOrientations {
        if (self.forceLandscape) {
            return UIInterfaceOrientationMaskLandscapeLeft;
        } else {
            //You can just allow Portrait.
            return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskPortrait;
        }
    }
    
    // Notifies when rotation begins, reaches halfway point and ends.
    - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
        //save new orientation
        _myOrientation = toInterfaceOrientation;
        [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    }
    
    - (IBAction)buttonPress:(id)sender {
        self.forceLandscape = !self.forceLandscape;
    
        if (self.forceLandscape) {
            _myOrientation = UIInterfaceOrientationMaskLandscapeLeft
        } else {
            //just do nothing
        }
    
        //call this to update orientation
        [UIViewController attemptRotationToDeviceOrientation];
    }
    

    【讨论】:

    • 之前尝试过尝试方法,但没有成功。它甚至不调用 supportInterfaceOrientation 和 willRotateToInterfaceOrientation。不错的尝试
    • 是的,你是对的。似乎 attemp 方法不会引起那些回调
    • 玩了一圈,发现这个尝试RotationToDeviceOrientation确实会旋转ui,只有事先旋转了设备本身。需要想办法在不移动设备的情况下旋转它
    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    相关资源
    最近更新 更多