萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

iOS 倒計時器實戰:NSTimer 驅動的午夜倒數 UI 實現

專案建立

  1. Xcode → New Project → iOS → View-Based Application
  2. 專案命名:MinutesToMidnight

控制器代碼

MinutesToMidnightViewController.h

#import 

@interface MinutesToMidnightViewController : UIViewController {
    NSTimer *timer;
    IBOutlet UILabel *countdownLabel;
}
@property (nonatomic, retain) UILabel *countdownLabel;
@property (nonatomic, retain) NSTimer *timer;
- (void)onTimer;
@end

MinutesToMidnightViewController.m

#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

Interface Builder 界面搭建

  1. 雙擊 MinutesToMidnightViewController.xib 打開 IB。
  2. View 背景設為黑色(Attributes Inspector → Background)。
  3. 從 Library 拖入 Label 到 View 中心,字體顏色設紅色、對齊居中。
  4. 連接 Outlet:選中 Label → Connection Inspector → New Referencing Outlet 拖線到 File's Owner → 選擇 countdownLabel。
  5. Save & Close IB。

運行效果

啟動後顯示大號紅色數碼管風格倒計時,每秒更新,精確倒數至當日 24:00:00。

現代 Swift 改寫 (iOS 13+ / Swift 5)

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 模式。
  • 字體文件需加入 Target → Build Phases → Copy Bundle Resources,並在 Info.plist 添加 UIAppFonts 陣列。
  • 時區邊界情況(夏令時、跨日)建議用 Calendar 計算「明天 00:00」再取 timeIntervalSinceNow 更稳健。
copyright © 萬盛學電腦網 all rights reserved