iOS: How to run a function after Device has Rotated (Swift)

后端 未结 3 1193
傲寒
傲寒 2020-12-02 16:52

I have one UIView which is not using Auto-Layout and some components are displayed based on their percent of X and Y co-ordinates from the main view.

Previously I wo

相关标签:
3条回答
  • 2020-12-02 16:53

    The viewWillTransitionToSize delegate method gets called with a UIViewControllerTransitionCoordinator conforming object. A method that protocol declares is animateAlongsideTransition(_:animation, completion:). You can use that to have code execute after the transition is complete.

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: nil) { _ in
            // Your code here
        }
    }
    
    0 讨论(0)
  • 2020-12-02 16:58

    Above answer https://stackoverflow.com/a/26944087/6583492 is absolutely right, thanks to Acey and Moonwalkr. But for swift 3.0 it will looks like the following

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: nil) { _ in
            // Your code here
        }
    }
    
    0 讨论(0)
  • 2020-12-02 17:19

    Although not asked for here Objective C version:

    - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
    
        // change any properties on your views
    
    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
        if( UIDeviceOrientationIsPortrait(orientation) ) {
            NSLog(@"portrait");
        } else {
            NSLog(@"landscape");
        }  
    }];
    }
    
    0 讨论(0)
提交回复
热议问题