Search code examples
iosobjective-cxcodelockinguitoolbar

Xcode Objective C: Locking Landscape in a Toolbar after a gesture


I want to create a toolbar that has a locking landscape method and an unlock. How can I go about this? I also just want it to display after a swipe gesture. I have the swipe gesture figured out but having trouble figuring out how to lock landscape after the user presses the button. It’s a app that has autorotate and want to keep it until the user wants to lock landscape. Where should I call or create this method? Do I need create another UIViewController and call it in the main one?


Solution

  • You can override shouldAutorotate method on the UIViewController.

    https://developer.apple.com/documentation/uikit/uiviewcontroller/1621419-shouldautorotate?changes=_3&language=objc

    Here is the sample ViewController with one button to lock/unlock rotation.

    @interface ViewController (){
        bool rotationLocked;
    }
    
    @property (weak, nonatomic) IBOutlet UIButton *lockButton;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    - (IBAction)togleRotationLock:(id)sender {
        rotationLocked = !rotationLocked;
        if (rotationLocked)
            [_lockButton setTitle:@"Ulock Rotation" forState:UIControlStateNormal];
        else
            [_lockButton setTitle:@"Lock Rotation" forState:UIControlStateNormal];
    }
    
    - (bool)shouldAutorotate{
        return !rotationLocked;
    }
    
    @end
    

    Additionally you can override the supportedInterfaceOrientations if you need to set specific orientation.

    https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?changes=_3&language=objc