iOS 强行设置设备横竖屏

    科技2024-11-18  8

    强制横竖屏

    强制横竖屏的对象是设备硬件。在UIDevice.h中可以找到 orientation参数。它可以控制着设备的方向。

    @property(nonatomic,readonly) UIDeviceOrientation orientation API_UNAVAILABLE(tvos); // return

    然而orientation 是一个只读的参数,无法直接赋值。根据Objective-C 的KVC属性。可以使用setValue方法对orientation赋值

    - (void)setValue:(nullable id)value forKey:(NSString *)key;

    orientation是 枚举UIDeviceOrientation 属性。

    typedef NS_ENUM(NSInteger, UIInterfaceOrientation) { UIInterfaceOrientationUnknown = UIDeviceOrientationUnknown, UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait, UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown, UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight, UIInterfaceOrientationLandscapeRight = UIDeviceOrientationLandscapeLeft } API_UNAVAILABLE(tvos);

    Demo代码如下:

    // 强制竖屏 [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationPortrait] forKey:@"orientation"]; // 强制向右 [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"]; // 强制向左 [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeLeft] forKey:@"orientation"];

    扩展一:监听横竖屏状态

    - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. // 添加横竖屏状态变化的通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil]; } - (void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; // 移除横竖屏状态变化的通知 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil]; } - (void)deviceOrientationDidChange:(NSNotification *)notification { //横竖屏监听回调 UIDevice *device = [UIDevice currentDevice]; switch (device.orientation) { case UIDeviceOrientationLandscapeLeft: // 向左橫屏 break; case UIDeviceOrientationLandscapeRight: // 向右橫屏 break; case UIDeviceOrientationPortrait: // 竖屏 break; default: break; } }

     

    Processed: 0.028, SQL: 8