MinutesToMidnight#import
@interface MinutesToMidnightViewController : UIViewController {
NSTimer *timer;
IBOutlet UILabel *countdownLabel;
}
@property (nonatomic, retain) UILabel *countdownLabel;
@property (nonatomic, retain) NSTimer *timer;
- (void)onTimer;
@end
#import "MinutesToMidnightViewController.h"
@implementation MinutesToMidnightViewController
@synthesize timer, countdownLabel;
- (void)viewDidLoad {
[super viewDidLoad];
// 數碼管風格字體(需專案包含字體文件並配置 Info.plist Fonts provided by application)
[countdownLabel setFont:[UIFont fontWithName:@"DBLCDTempBlack" size:128.0]];
countdownLabel.text = @"00:00:00";
// 每秒觸發一次
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(onTimer)
userInfo:nil
repeats:YES];
}
- (void)onTimer {
NSDate *now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
NSInteger hour = [comps hour];
NSInteger minute = [comps minute];
NSInteger second = [comps second];
// 計算距離午夜剩餘時間
second = 60 - second;
minute = 59 - minute;
hour = 23 - hour;
// 處理進位(如秒=60→分+1,秒=0)
if (second == 60) { second = 0; minute++; }
if (minute == 60) { minute = 0; hour++; }
if (hour == 24) { hour = 0; }
[gregorian release];
countdownLabel.text = [NSString stringWithFormat:@"%02ld:%02ld:%02ld", (long)hour, (long)minute, (long)second];
}
- (void)dealloc {
[timer release];
[countdownLabel release];
[super dealloc];
}
@end
MinutesToMidnightViewController.xib 打開 IB。New Referencing Outlet 拖線到 File's Owner → 選擇 countdownLabel。啟動後顯示大號紅色數碼管風格倒計時,每秒更新,精確倒數至當日 24:00:00。
class CountdownViewController: UIViewController {
@IBOutlet weak var label: UILabel!
private var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
label.font = UIFont(name: "DBLCDTempBlack", size: 128) ?? .monospacedDigitSystemFont(ofSize: 128, weight: .regular)
label.textColor = .systemRed
label.text = "00:00:00"
startTimer()
}
private func startTimer() {
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
self?.updateCountdown()
}
RunLoop.main.add(timer!, forMode: .common) // 確保滑動時不暫停
}
private func updateCountdown() {
let now = Date()
let cal = Calendar.current
let comps = cal.dateComponents([.hour, .minute, .second], from: now)
let h = 23 - (comps.hour ?? 0)
let m = 59 - (comps.minute ?? 0)
let s = 60 - (comps.second ?? 0)
// 進位處理同 OC 版
label.text = String(format: "%02d:%02d:%02d", h, m, s)
}
deinit { timer?.invalidate() }
}
NSTimer/Timer 預設在 RunLoopMode.default 運行,ScrollView 滑動時會暫停 → 加入 .common 模式。Info.plist 添加 UIAppFonts 陣列。Calendar 計算「明天 00:00」再取 timeIntervalSinceNow 更稳健。