简体   繁体   English

iOS-如何在不同的视图控制器中启动计时器

[英]Ios - How to start a timer in different view controllers

I have a view controller A that contains a start button that when clicked uses the 'show' segue to display the next view. 我有一个视图控制器A,其中包含一个开始按钮,单击该按钮时将使用“显示”按钮来显示下一个视图。 In the other view controller BI have a timer. 在另一个视图控制器BI中有一个计时器。 How can I get the timer in view controller B to start once the start button is clicked in view controller A. So far I have the start button and timer in the same view controller, however, I want to move the timer to view controller B. Any help on how to do this ? 单击视图控制器A中的启动按钮后,如何在视图控制器B中启动计时器。到目前为止,我在同一视图控制器中具有启动按钮和计时器,但是,我想将计时器移至视图控制器B有什么帮助吗?

Use below code. 使用下面的代码。 //FirstViewController.m //FirstViewController.m

#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController()
@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)startButton:(id)sender {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SecondViewController *controller = [storyBoard instantiateViewControllerWithIdentifier:@"SecondViewController"];
    [controller startTimer];
    [self.navigationController pushViewController:controller animated:YES];
}

// SecondViewController.h // SecondViewController.h

#import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController {

}

-(void)startTimer;

@end

// SecondViewController.m // SecondViewController.m

#import "SecondViewController.h"

@interface SecondViewController ()

@property (nonatomic,retain) NSTimer *timer;
@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}


-(void)startTimer {

    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                  target:self
                                                selector:@selector(timerFired:)
                                                userInfo:nil
                                                 repeats:YES];
    }
}
-(void)stopTimer {
    if ([_timer isValid]) {
        [_timer invalidate];
    }
    _timer = nil;
}

- (void)timerFired:(NSTimer *)timer {
     NSLog(@"%@",timer.fireDate);
}

-(void) viewWillDisappear:(BOOL)animated {
    [self stopTimer];
}

If the button shows the next UIViewController and also should start a timer there, why not just start the timer in the viewWillAppear method of the next ViewController? 如果该按钮显示下一个UIViewController,并且还应该在该位置启动计时器,为什么不直接在下一个ViewController的viewWillAppear方法中启动计时器?

Alternatively use the prepareForSegue in the first viewController 或者在第一个viewController中使用prepareForSegue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{
    if ([segue.identifier isEqualToString:@"show_segue_id_from_storyboard"]) {
        ViewController2 *yourNextViewController = segue.destinationViewController;
        [yourNextViewController startTimer];
    }
}

Will call the startTimer function when your segue is triggered from the button click. 通过单击按钮触发segue时,将调用startTimer函数。

        // First VC prepareForSegue
 -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
        {
             if([segue.identifier isEqualToString:@"your segue"])
             {
                SecondVC *vc = (SecondVC *)segue.destinationViewController;
                 [vc.timer startTimer:nil];
             }
        }

        //Add below line in  second Vc 's .h file.
    @property (nonatomic, strong) NSTimer *timer;
     - (void)stopTimer:(id)sender; 
    - (void)timerFired:(NSTimer *)timer; 

        // Second VC's Public Methods
        @interface SecondVC ()
        @end

        @implementation SecondVC

        - (void)startTimer:(id)sender {
            if (!self.timer) {
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                          target:self
                                                        selector:@selector(timerFired:)
                                                        userInfo:nil
                                                         repeats:YES];
            }
        }

        - (IBAction)stopTimer:(id)sender {
            if ([self.timer isValid]) {
                [self.timer invalidate];
            }
            self.timer = nil;
        }

        - (void)timerFired:(NSTimer *)timer {
            NSLog(@"Timer fired");
        }

In the other view controller BI have a timer. 在另一个视图控制器BI中有一个计时器。 How can I get the timer in view controller B to start once the start button is clicked in view controller A. 一旦在视图控制器A中单击开始按钮,如何在视图控制器B中使计时器启动。

Why does the timer need to be part of any view controller? 为什么计时器需要成为任何视图控制器的一部分? Considering that multiple controllers need to access it, and it's probably part of your app's logic rather than being directly related to the user interface, it would make more sense to move the timer into your app's model. 考虑到需要多个控制器来访问它,并且它可能是应用程序逻辑的一部分,而不是与用户界面直接相关,因此将计时器移入应用程序模型会更有意义。 View controller A can then tell the model that the start button was clicked, and view controller B can use KVO or notifications to watch for a change in the model that's triggered when the timer fires. 然后,视图控制器A可以告诉模型单击了开始按钮,并且视图控制器B可以使用KVO或通知来监视计时器触发时触发的模型更改。 Neither controller needs to even know that the timer itself even exists -- it simply becomes an implementation detail of the model. 任何一个控制器甚至都不需要知道计时器本身是否存在-它只是成为模型的实现细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM