appdelegate.m
+ (AppDelegate *)sharedInstance {
return (AppDelegate *)[UIApplication sharedApplication].delegate;
}
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
return _orientationMask;
}
- (void)setOrientationMask:(UIInterfaceOrientationMask)orientationMask {
if (_orientationMask == orientationMask) {
return;
}
_orientationMask = orientationMask;
UIDeviceOrientation orient = UIDeviceOrientationUnknown;
if (UIInterfaceOrientationMaskLandscape & orientationMask) {
switch ([UIDevice currentDevice].orientation) {
case UIDeviceOrientationLandscapeLeft:
orient = UIDeviceOrientationLandscapeLeft;
break;
case UIDeviceOrientationLandscapeRight:
orient = UIDeviceOrientationLandscapeRight;
break;
default:
orient = UIDeviceOrientationLandscapeRight;
break;
}
} else if (UIInterfaceOrientationMaskPortrait & orientationMask) {
orient = UIDeviceOrientationPortrait;
} else if (UIInterfaceOrientationMaskPortraitUpsideDown & orientationMask) {
orient = UIDeviceOrientationPortraitUpsideDown;
}
[[UIDevice currentDevice] setValue:@(UIDeviceOrientationUnknown) forKey:@"orientation"];
[[UIDevice currentDevice] setValue:@(orient) forKey:@"orientation"];
[UIViewController attemptRotationToDeviceOrientation];
}
appdelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate>
+ (AppDelegate *)sharedInstance;
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, assign) UIInterfaceOrientationMask orientationMask;
@end
调用:
[AppDelegate sharedInstance].orientationMask = UIInterfaceOrientationMaskPortrait;
本文介绍了一个iOS应用中如何使用AppDelegate来设置和管理应用的方向。通过重写supportedInterfaceOrientationsForWindow方法,可以指定应用支持的设备方向。此外,通过setOrientationMask方法,可以在运行时动态更改应用的方向。

被折叠的 条评论
为什么被折叠?



