方向改变触发的方法

12

是否有一种方法可以在iOS设备方向改变时运行方法?

我想仅更改屏幕上的某些对象方向,而不是其他对象。

我应该使用哪些代理等?

祝好 -一个新手

6个回答

31

取决于你想在什么时候做出反应:

如果在旋转之前,从UIViewController中覆盖

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
 // do something before rotation
}

如果你想在旋转之后执行某些操作:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
 // do something after rotation
}

参考资料:

http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instm/UIViewController/willRotateToInterfaceOrientation:duration:


4
这些方法已被弃用。 - Cameron Lowell Palmer
1
在iOS 8.0中已被弃用。 - onmyway133

6

UIDevice会发布UIDeviceOrientationDidChangeNotification通知。

UIApplication会发布UIApplicationWillChangeStatusBarOrientationNotificationUIApplicationDidChangeStatusBarOrientationNotification通知,并且每个通知都有相关联的委托回调函数。

UIViewController如果是窗口管理的控制器层次结构的一部分,将会收到由UIDevice通知触发的几个与方向相关的调用。

如果您已经使用了UIViewController,请实现一些与方向相关的方法;否则,请注册UIDevice通知。最重要的UIViewController方法是shouldAutorotateToInterfaceOrientation,因为如果它返回NO,其他方法就不会被调用。


我更喜欢注册为观察者以接收方向通知。所以我投票支持这个答案。 - AechoLiu

0

你可能正在寻找的方法是willRotateToInterfaceOrientation:。请仔细阅读相关文档。


0

UIViewController在旋转之前会收到willRotateToInterfaceOrientation:duration:的通知,而在旋转完成后会收到didRotateFromInterfaceOrientation:的通知。

要配置其他动画,请使用willAnimateRotationToInterfaceOrientation:duration:willAnimateFirstHalfOfRotationToInterfaceOrientation:duration:didAnimateFirstHalfOfRotationToInterfaceOrientation:willAnimateSecondHalfOfRotationFromInterfaceOrientation:duration:。后者用于两步动画,通常在您有标题或页脚视图需要在主转换动画中移出屏幕时使用。


0

只需使用此代码片段来检查方向更改。

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.currentDevice().orientation.isLandscape.boolValue {
        print("Landscape")
    } else {
        print("Portrait")
    }
}

这是不正确的,因为在从纵向到横向的转换时,viewWillTransitionToSize仍将打印纵向。 - Bijoy Thangaraj

0
我的沙盒应用程序: https://github.com/comonitos/programatical_device_orientation 解决方案很简单:
在接口(h文件)中:
BOOL rotated;

在实现文件(m文件)中:

  1. 重写

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return rotated; }

2. 调用[self setup]

-(void) setup 
{
   rotated = YES;
   [[UIDevice currentDevice] setOrientation:UIDeviceOrientationLandscapeLeft];
   rotated = NO;
}

你不应该在 shouldAutorotateToInterfaceOrientation 方法中做太多的事情,只需要告诉操作系统你是否支持方向变化即可。此外,在iOS6中这个方法已经被弃用了。http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/DeprecationAppendix/AppendixADeprecatedAPI.html#//apple_ref/occ/instm/UIViewController/shouldAutorotateToInterfaceOrientation: - mahboudz
是的,现在可以了。从那时起,我一直在转换视图。 - Tim Kozak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接