How to Perform Segue With Delay

送分小仙女□ 提交于 2019-11-27 17:46:56

问题


In my storyboard, I have a view as a splash screen. In this view, I already have a button like "Open Application" that is opening the menu view with a modal segue. But I also want screen to perform segue automatically, like after 2 seconds view appears.

Some code here:

- (void)viewDidAppear:(BOOL)animated
{
    [self performSegueWithIdentifier:@"splashScreenSegue" sender:self];
}

As you can see, I already use performSegueWithIdentifier but it performs immediately. Is there a method to make it delay?

Thanks in advance.


回答1:


You can use GCD's dispatch_after to execute your segue code 2 seconds after the view appears, e.x:

- (void)viewDidAppear:(BOOL)animated 
{
    [super viewDidAppear:animated];

    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self performSegueWithIdentifier:@"splashScreenSegue" sender:self];
    });
}

Additionally, please make sure that you remember to call the super implementation when overriding UIViewController's life cycle methods.




回答2:


I think there is a better approach which lets the controller itself to handle dispatching issues. You can achieve it like this:
first create a method like this which later you will use its selector

- (void)showAnotherViewController{  
    [self performSegueWithIdentifier:@"yourSegueToAnotherViewController" sender:self];
}  

Then when you want to show another view controller after delay use this line of code inside your current view controller:

[self performSelector:@selector(showAnotherViewController) withObject:nil afterDelay:yourDelayInSeconds];



回答3:


In Swift 5.1 you can achieve that by calling:

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [unowned self] in
            self.performSegue(withIdentifier: "your segue id", sender: nil)
        }


来源:https://stackoverflow.com/questions/10025423/how-to-perform-segue-with-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!