Học viên hỏi: Ứng dụng có nhiều màn hình. Các màn hình đều là portrait hoặc landscape. Tuy nhiên có một màn hình cần buộc phải hiển thị landscape. Làm thế nào?

Học lập trình iOS trực tuyến

Trả lời: Chúng ta có thể ghi đè thuộc tính orientation của đối tượng UIDevice. Ở màn hình X, muốn màn hình này luôn là landscape thì code như sau

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

Code thực tế sẽ phức tạp hơn một chút vì cần phải kiểm tra orientation của màn hình trước đó. Code thực tế đây. https://github.com/TechMaster/SwitchLandscapePortrait

@interface MovieDetailVC ()
{
    UIImageView * poster;
    UIDeviceOrientation previousOrientation;
}
@end

@implementation MovieDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    poster = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Poster.jpg"]];
    [self.view addSubview:poster];
}

- (void) viewWillAppear:(BOOL)animated {
    UIDevice* device = [UIDevice currentDevice];
    if (device.orientation ==  UIInterfaceOrientationPortrait) {
        previousOrientation = device.orientation;
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
        [device setValue:value forKey:@"orientation"];
    }
    
}

- (void) viewDidDisappear:(BOOL)animated {
    UIDevice* device = [UIDevice currentDevice];
    if (previousOrientation != device.orientation) {
        NSNumber *value = [NSNumber numberWithInt:previousOrientation];
        [device setValue:value forKey:@"orientation"];
    }
}

@end