I have three view controllers(VC). My second VC has a start button and third VC I set a label top right corner for a time.If I click the start button(in second VC) then the time should run when I move to the third VC. How to do this? For a quiz app.
Asked
Active
Viewed 49 times
1 Answers
1
You can do this easily:
Use storyboard create UI:
The code is below:
ViewController2.m:
#import "ViewController2.h"
@interface ViewController2 ()
{
NSTimer *timer;
int time_count;
}
@property (weak, nonatomic) IBOutlet UILabel *time_label;
@end
@implementation ViewController2
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(handleTimer:)
userInfo:nil
repeats:YES];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (void)handleTimer:(id )sender {
_time_label.text = [NSString stringWithFormat:@"%d", time_count++];
}
@end
The result is like this:
Swift 3
The main code:
import UIKit
class ViewController2: UIViewController {
@IBOutlet weak var time_label: UILabel!
var time_count = 0
override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerHandler), userInfo: nil, repeats: true)
}
func timerHandler() {
self.time_count += 1
self.time_label.text = "\(self.time_count)"
}
}
aircraft
- 20,821
- 22
- 79
- 154