iOS 开发 计时器秒数 oc代码
以下是一个简单的iOS开发中使用Objective-C语言编写的计时器秒数的示例代码:
// ViewController.h 文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *timerLabel;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger seconds;
- (IBAction)startTimer:(id)sender;
- (IBAction)stopTimer:(id)sender;
- (IBAction)resetTimer:(id)sender;
@end
// ViewController.m 文件
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化秒数
self.seconds = 0;
}
- (IBAction)startTimer:(id)sender {
// 使用每秒触发一次的定时器
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES];
}
- (IBAction)stopTimer:(id)sender {
// 停止定时器
[self.timer invalidate];
self.timer = nil;
}
- (IBAction)resetTimer:(id)sender {
// 重置秒数并更新标签
self.seconds = 0;
[self updateTimerLabel];
}
- (void)updateTimerLabel {
// 更新秒数并显示在标签上
self.seconds++;
self.timerLabel.text = [NSString stringWithFormat:@"%ld", (long)self.seconds];
}
@end
上述代码中,首先在ViewController.h文件中定义了一个ViewController类,该类继承自UIViewController。在类中定义了一个timerLabel标签用于显示秒数,一个timer定时器用于计时,一个seconds整型属性用于存储秒数。
然后,在ViewController.m文件中实现了计时器的开始、停止和重置功能。startTimer方法使用NSTimer类的scheduledTimerWithTimeInterval方法创建一个每秒触发一次的定时器,并指定了updateTimerLabel方法作为定时器触发时调用的方法。stopTimer方法停止定时器,resetTimer方法重置秒数并更新标签。updateTimerLabel方法在定时器触发时会被调用,该方法会更新秒数并显示在标签上
原文地址: http://www.cveoy.top/t/topic/iQwf 著作权归作者所有。请勿转载和采集!