0

私は時計アプリを作成しています。コンポーネント (時間、分、秒) を間隔を空けて現在の時刻を表示したいと考えています。それを行う唯一の方法は、時間を 3 つの文字列に分けることだと思います。それ、どうやったら出来るの?

- (void)updateTime {

    [updateTimer invalidate];
    updateTimer = nil;

    currentTime = [NSDate date];
    NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
    [timeFormatter setTimeStyle:NSDateFormatterMediumStyle];
    lblTime.text = [timeFormatter stringFromDate:currentTime];

    updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];

}
4

3 に答える 3

4

A couple things here:

1 ) if you want a constantly running timer, don't invalidate it each time "updateTime" is called (and only call scheduledTimerWithTimeInterval: once... instead of at the end of each time "updateTime" is called).

2 ) it looks like you have a single label for displaying your time. You should make your timeFormatter an ivar (instance variable, so it's created and set only once) and then you can set the format via:

timeFormatter.dateFormat = @"HH:mm:ss";

And you should be all set.

Your new updateTime method could look like this:

- (void)updateTime {    
    currentTime = [NSDate date];
    lblTime.text = [timeFormatter stringFromDate:currentTime];    
}

3 ) If you want three different labels, you need to declare IBOutlets for the three labels and have three different date formatters. For example:

@interface YourViewController : UIViewController ()
{
    IBOutlet UILabel * hourLabel; // you need to connect these in your XIB/storyboard
    IBOutlet UILabel * minuteLabel;
    IBOutlet UILabel * secondLabel;

    NSDateFormatter * hourFormatter;
    NSDateFormatter * minuteFormatter;
    NSDateFormatter * secondFormatter;
}

Then, in your "viewDidLoad:" method, set up your formatters:

hourFormatter = [[NSDateFormatter alloc] init;
hourFormatter.dateFormatter = @"HH";
minuteFormatter = [[NSDateFormatter alloc] init;
minuteFormatter.dateFormatter = @"mm";
secondFormatter = [[NSDateFormatter alloc] init;
secondFormatter.dateFormatter = @"ss";

And finally, in your "updateTime" method:

- (void)updateTime {    
    currentTime = [NSDate date];
    if(hourFormatter)
    {
        if(hourLabel)
        {
            hourLabel.text = [hourFormatter stringFromDate: currentTime];
        } else {
            NSLog( @"you need to connect your hourLabel outlet in your storyboard or XIB" );
        }
    } else {
        NSLog( @"you need to allocate and init and set hourFormatter");
    }
    minuteLabel.text = [minuteFormatter stringFromDate: currentTime];
    secondLabel.text = [secondFormatter stringFromDate: currentTime];
}
于 2013-05-18T16:55:20.880 に答える