是否有一种方法可以在iOS设备方向改变时运行方法?
我想仅更改屏幕上的某些对象方向,而不是其他对象。
我应该使用哪些代理等?
祝好 -一个新手
取决于你想在什么时候做出反应:
如果在旋转之前,从UIViewController中覆盖:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
// do something before rotation
}
如果你想在旋转之后执行某些操作:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
// do something after rotation
}
参考资料:
UIDevice
会发布UIDeviceOrientationDidChangeNotification
通知。
UIApplication
会发布UIApplicationWillChangeStatusBarOrientationNotification
和UIApplicationDidChangeStatusBarOrientationNotification
通知,并且每个通知都有相关联的委托回调函数。
UIViewController
如果是窗口管理的控制器层次结构的一部分,将会收到由UIDevice
通知触发的几个与方向相关的调用。
如果您已经使用了UIViewController
,请实现一些与方向相关的方法;否则,请注册UIDevice
通知。最重要的UIViewController
方法是shouldAutorotateToInterfaceOrientation
,因为如果它返回NO
,其他方法就不会被调用。
你可能正在寻找的方法是willRotateToInterfaceOrientation:。请仔细阅读相关文档。
UIViewController
在旋转之前会收到willRotateToInterfaceOrientation:duration:
的通知,而在旋转完成后会收到didRotateFromInterfaceOrientation:
的通知。
要配置其他动画,请使用willAnimateRotationToInterfaceOrientation:duration:
或willAnimateFirstHalfOfRotationToInterfaceOrientation:duration:
,didAnimateFirstHalfOfRotationToInterfaceOrientation:
和willAnimateSecondHalfOfRotationFromInterfaceOrientation:duration:
。后者用于两步动画,通常在您有标题或页脚视图需要在主转换动画中移出屏幕时使用。
只需使用此代码片段来检查方向更改。
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.currentDevice().orientation.isLandscape.boolValue {
print("Landscape")
} else {
print("Portrait")
}
}
viewWillTransitionToSize
仍将打印纵向。 - Bijoy ThangarajBOOL rotated;
在实现文件(m文件)中:
重写
- (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