LEDClock,儲存路徑預設 ~/Documents。NSTimer,每秒觸發更新。UILabel (IBOutlet),負責格式化時間字串並顯示。#import <UIKit/UIKit.h>
@class LEDClockViewController;
@interface LEDClockAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
LEDClockViewController *viewController;
NSTimer *timer;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet LEDClockViewController *viewController;
- (void)onInterval;
@end
#import "LEDClockAppDelegate.h"
#import "LEDClockViewController.h"
@implementation LEDClockAppDelegate
@synthesize window, viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(onInterval)
userInfo:nil
repeats:YES];
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void)onInterval {
[viewController interval];
}
- (void)dealloc {
[timer release];
[viewController release];
[window release];
[super dealloc];
}
@end
#import <UIKit/UIKit.h>
@interface LEDClockViewController : UIViewController {
IBOutlet UILabel *timerLabel;
}
@property (nonatomic, retain) UILabel *timerLabel;
- (void)interval;
@end
#import "LEDClockViewController.h"
@implementation LEDClockViewController
@synthesize timerLabel;
- (void)interval {
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [cal components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
fromDate:[NSDate date]];
int h = [comp hour], m = [comp minute], s = [comp second];
timerLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", h, m, s];
[cal release];
}
- (void)viewDidLoad {
[super viewDidLoad];
// 設定 LED 字體(需專案包含 DBLCDTempBlack.ttf)
timerLabel.font = [UIFont fontWithName:@"DBLCDTempBlack" size:50.0];
timerLabel.text = @"電子時鐘"; // 初始文字
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
return YES; // 支援所有旋轉
}
- (void)dealloc {
[timerLabel release];
[super dealloc];
}
@end
LEDClockViewController.xib → 雙擊 View → 背景設為黑色。timerLabel。DBLCDTempBlack.ttf 加入專案,並在 Info.plist 加入 Fonts provided by application 陣列項。Info.plist 加入 UIBackgroundModes = audio 或 location 維持後台計時(需正當理由)。[timer invalidate],回前台再重建。CABasicAnimation 讓冒號閃爍或數字翻轉。NSTimeZone 切換顯示多城市時間。本例展示經典的「Timer + ViewController + XIB」模式。關鍵點:NSTimer 在 RunLoop 的 NSRunLoopCommonModes 運行(預設),滑動 ScrollView 時不會暫停;自訂字體需正確嵌入專案;記憶體管理遵循 MRC 規範(本例為舊版代碼),現代專案請改用 ARC + weak 屬性。此架構易於擴展為世界時鐘、碼錶、倒數計時器等應用。