이 코드가 있습니다.
NSDate *now = [NSDate date];
static NSDateFormatter *dateFormatter;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"h:mm:ss";
}
recordStatusLabel.text = [dateFormatter stringFromDate:now];
NSLog(@"Time now: %@", [dateFormatter stringFromDate:now]);
현재 시간을 계산합니다. 이 형식으로 시작하도록 어떻게 변경할 수 있습니까?
00:00:00 (시 : 분 : 초)
A로부터 NSString
변수 :
예 : 내 변수에 대해이 값을 얻었습니다.
NSString * time = @"02:16:23";
그런 다음 카운터는 02:16:24까지 카운트를 계속합니다. . . 02:20:13
NSTimer
반복 옵션을 사용하여 클래스 인스턴스를 만들고 이벤트 발생 시간을 1 초로 설정 YES
합니다. 이벤트 처리에서 레이블을 현재 시간으로 업데이트하십시오. 기능이 완료되면 타이머를 무효화하여 이벤트 발생을 중지합니다.
다음은 NSTimer
클래스의 인스턴스를 만드는 코드입니다 .
NSTimer *countUpTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:@selector(countUpTimerFired:) userInfo:nil repeats:YES];
다음은 이벤트 처리 방법입니다.
- (void)countUpTimerFired:(id)sender {
dispatch_async(dispatch_get_main_queue(), ^{
recordStatusLabel.text = [dateFormatter stringFromDate:[NSDate date]];
});
}
dateFormatter
및 countUpTimer
클래스 변수로 유지하십시오 .
이것은 현재 장치 시간에서 시간을 시작할 때 필요한 기능을 달성하는 간단한 방법입니다. 따라서 레이블에서 값을 가져오고 값을 증가시킨 다음 다시 문자열로 변환하기 위해 추가 노력이 필요하지 않습니다.
편집하다:
다른 시간 값이나 문자열에서 카운터를 시작하려면 정수 변수를 유지하여 시간 값을 초 단위로 유지할 수 있습니다. 그런 다음 타이머 이벤트가 호출 될 때 (매초) 값을 증가시킨 다음 해당 정수를 시간 문자열로 변환합니다.
초기 값에 대한 코드는 다음과 같습니다.
NSString *timeString = recordStatusLabel.text; //contains a string in time format like @"2:16:23" or @"00:00:00" or current time or any other value.
NSArray *timeComponents = [timeString componentsSeparatedByString:@":"];
int timeInSeconds = [timeComponents[0] intValue]*3600 + [timeComponents[1] intValue]*60 + [timeComponents[2] intValue];
타이머의 이벤트 처리에서 :
- (void)countUpTimerFired:(id)sender {
timeInSeconds++;
int hours = timeInSeconds/3600;
int minutes = (timeInSeconds%3600)/60;
int seconds = timeInSeconds%60;
dispatch_async(dispatch_get_main_queue(), ^{
[recordStatusLabel setText:[NSString stringWithFormat:@"%d:%02d:%02d", hours, minutes, seconds]];
});
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다