我有三个视图控制器(VC)。我的第二个VC有一个开始按钮和第三个VC我设置了一个标签右上角一段时间。如果我点击开始按钮(在第二个VC中),那么当我移动到第三个VC时应该运行时间。这该怎么做? 对于测验应用程序。
答案 0 :(得分:1)
您可以轻松完成此操作:
使用storyboard create UI:
代码如下:
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
结果如下:
Swift 3
主要代码:
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)"
}
}