Timer to return to previous view in xcode [duplicate]

不打扰是莪最后的温柔 提交于 2019-12-25 19:36:45

问题


Hello I am extremely new to xcode and programming in general. I am trying to create a simple app that has two view controllers. The first ViewController in the story board has no code only a navigation bar and a next button which has a modal connecting to VideoController. I have added this code to the VideoController.m file

- (void)viewDidLoad
{
[super viewDidLoad];
//code added

[NSTimer scheduledTimerWithTimeInterval:3.0
                       target:self
                       selector:@selector(goBack)
                       userInfo:nil repeats:NO];

}

//code added
-(void)goBack{
 [self.navigationController popViewControllerAnimated:YES];
}

However this is not bringing me back to the previous page after the 3 second delay as i had hoped. Any suggestions? I dont know what I am missing


回答1:


Edit - you don't really have to retain the timer, but retaining it will allow you to cancel it later by invalidating the timer.

First of all you have to retain your timer. Add it as a property to your class

in .h

@property (strong, nonatomic) NSTimer *timer;

in .m

self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0
                       target:self
                       selector:@selector(goBack)
                       userInfo:nil repeats:NO];

Second you can use dispatch_after instead

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    [self.navigationController popViewControllerAnimated:YES];
});

And the last, do not do this. Whatever you are doing with your video controller, you don't want people to get thrown out of controllers for no reason. You probably should wait until the video has finished playing and dismiss your controller on the playback end notification.




回答2:


You don't need to use a timer to fire an action once, GCD and dispatch_after() works juts as well without needing to use local variables to store the timer or to invalidate it.

For example

If you use a segue to push the second view controller onto the stack you can dismiss it from the prepareForSegueMethod.

I've done it this way:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqual:@"FirstToSecond"]) {
        // Use GCD to dispatch a call to pop the view controller
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    }
}

You can download a working example of this.



来源:https://stackoverflow.com/questions/22879150/timer-to-return-to-previous-view-in-xcode

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