强制横竖屏的对象是设备硬件。在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"];