我正在使用Objective-C来制作秒表。我已经有一个带3个按钮的基本秒表:启动,停止和重置。这是我的viewcontroller.m代码:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
-(IBAction)Start:(id)start
{
Timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(addingthetime) userInfo:nil repeats:YES];
}
-(IBAction)Stop:(id)sender
{
[Timer invalidate];
}
-(IBAction)Restart:(id)sender
{
[Timer invalidate];
addingtheTime = 0;
Label.text = [NSString stringWithFormat:@"0.00"];
}
-(void)addingthetime
{
addingtheTime = addingtheTime + 0.01;
Label.text = [NSString stringWithFormat:@"%.2f", addingtheTime];
}
@end
这是我的viewcontroller.h代码:
#import <UIKit/UIKit.h>
float addingtheTime;
@interface ViewController : UIViewController
{
IBOutlet UILabel *Label;
NSTimer *Timer;
}
@end
所以我的问题是如何点击“开始”按钮执行以下操作:
所以目标是只有一个启动和停止计时器的按钮,但我也希望标题也能改变。
不要担心重置按钮,因为我希望它自己保留。
PS。请清楚地解释一下,因为我觉得很难理解一些事情,而且我是初学者所以请尽量保持相当简单,谢谢,如果问题不明确,对不起。
答案 0 :(得分:0)
您可以使用button.tag
属性来实现此目的。默认情况下,button.tag
属性为0
。因此,假设0是定时器未启动时的状态,1是定时器启动时的状态。您可以根据自定义逻辑操作.tag属性。
-(IBAction)Start:(id)start
{
UIButton *button = (UIButton *)start;
if (button.tag == 0){
button.tag = 1;
[button setTitle:@"Stop" forControlState:UIControlStateNormal];
Timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(addingthetime) userInfo:nil repeats:YES];
}else {
button.tag = 0;
[button setTitle:@"Stop" forControlState:UIControlStateNormal];
//Invoke your method to stop Timer.
}
}
答案 1 :(得分:-3)
在ViewController.h中:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)addingthetime
{
addingtheTime = addingtheTime + 0.01;
Label.text = [NSString stringWithFormat:@"%.2f", addingtheTime];
}
- (IBAction)startOrStopAction:(UIButton *)sender {
// stop
if ([sender.titleLabel.text isEqualToString:@"stop"]) {
[Timer setFireDate:[NSDate distantFuture]];
[sender setTitle:@"start" forState:UIControlStateNormal];
}
// start
else {
if (!Timer) {
Timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(addingthetime) userInfo:nil repeats:YES];
}else {
[Timer setFireDate:[NSDate date]];
}
[sender setTitle:@"stop" forState:UIControlStateNormal];
}
}
@end
在ViewController.m中:
if(request.SubProperty !=null)
{
var result = SomeProvider.GetObjectById(request.SubProperty.Id);
}
结果:
在iPhone中:
在iPad中: