Change orientation programmatically with button - iOS

后端 未结 2 1612
误落风尘
误落风尘 2021-01-17 15:21

I have a view controller and I would like to have the following experience. Inside the view controller i got a button which force rotate the orientation to landscape right.

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-17 16:14

    I don't have a swift code. Below are the objective c code, It worked for me. You can convert it into swift as per your requirement.

    Ojective C

    UIInterfaceOrientation currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];    
    [UIViewController attemptRotationToDeviceOrientation];
    

    #Update

    Swift 4.0

    var value  = UIInterfaceOrientation.landscapeRight.rawValue
    if UIApplication.shared.statusBarOrientation == .landscapeLeft || UIApplication.shared.statusBarOrientation == .landscapeRight{
       value = UIInterfaceOrientation.portrait.rawValue
    }
    
    UIDevice.current.setValue(value, forKey: "orientation")
    UIViewController.attemptRotationToDeviceOrientation()
    

    Above code already tested by me and it is working fine. Incase above code is not worked for you, Then execute it after some delay using performSelector.

提交回复
热议问题