要理解 iOS 程式的行為,先要理解它是「怎麼跑起來的」。本文從 main 函式出發,走過啟動流程、生命週期委派,並以一個包含 Label、TextField、Button 與 AlertView 的完整範例說明各個階段的時機。
每一支 iOS App 的進入點都是 main,它主要負責三件事:
第三點是關鍵:App 啟動之後看起來「什麼都沒做」,其實是卡在事件迴圈中等你觸碰螢幕。所有 UI 事件的處理都在這個迴圈中被分派。
#import "CCLTestDelegate.h"
@interface CCLTestDelegate ()
{
UIView *_bgView;
UILabel *_lable;
UITextField *_tf;
UIButton *_button;
}
@end
@implementation CCLTestDelegate
// 當應用程式載入完成時觸發
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog(@"%s", __FUNCTION__);
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// 背景 view
_bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
_bgView.backgroundColor = [UIColor whiteColor];
[self.window addSubview:_bgView];
// Label
_lable = [[UILabel alloc] initWithFrame:CGRectMake(110, 50, 100, 40)];
_lable.backgroundColor = [UIColor grayColor];
_lable.layer.cornerRadius = 5;
_lable.layer.masksToBounds = YES;
_lable.text = @"lable";
[_bgView addSubview:_lable];
// TextField
_tf = [[UITextField alloc] initWithFrame:CGRectMake(110, 110, 100, 40)];
_tf.backgroundColor = [UIColor grayColor];
_tf.placeholder = @"輸入手機號碼";
_tf.keyboardType = UIKeyboardTypeNumberPad;
_tf.clearButtonMode = UITextFieldViewModeWhileEditing;
_tf.delegate = self;
_tf.tag = 100;
_tf.layer.cornerRadius = 5;
[_bgView addSubview:_tf];
// Button
_button = [UIButton buttonWithType:UIButtonTypeSystem];
_button.frame = CGRectMake(110, 170, 100, 40);
[_button setTitle:@"點我" forState:UIControlStateNormal];
[_button addTarget:self
action:@selector(click:)
forControlEvents:UIControlEventTouchUpInside];
_button.layer.cornerRadius = 5;
_button.layer.masksToBounds = YES;
_button.backgroundColor = [UIColor grayColor];
[_bgView addSubview:_button];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
小技巧:NSSelectorFromString(@"click:") 可以把「方法名字串」轉為 SEL,這是 KVO、中繼程式與某些動態框架的基礎。
// 點擊按鈕:判斷輸入框文字是否為 11 位
- (void)click:(UIButton *)button
{
// 1. 取得輸入框(透過 tag 查找)
UITextField *tf = (UITextField *)[button.superview viewWithTag:100];
// 2. 判斷長度
if (tf.text.length != 11) {
// title: 標題
// message: 提示內容
// delegate: 代理
// cancelButtonTitle: 取消鈕文字
// otherButtonTitles: 其他按鈕文字,可有多個
UIAlertView *alertView =
[[UIAlertView alloc] initWithTitle:@"警告"
message:@"手機號輸入有誤"
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"啊", @"確定", nil];
// alertViewStyle 可選值:
// UIAlertViewStyleDefault
// UIAlertViewStyleSecureTextInput
// UIAlertViewStylePlainTextInput
// UIAlertViewStyleLoginAndPasswordInput
alertView.alertViewStyle = UIAlertViewStyleSecureTextInput;
[alertView show];
}
}
// 點擊 alert 按鈕時觸發
- (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex
{
// 取消鈕的 index 為 0,其餘按鈕由上到下依序遞增
NSLog(@"buttonIndex %ld", (long)buttonIndex);
switch (buttonIndex) {
case 0: NSLog(@"取消鈕被點擊"); break;
case 1: NSLog(@"啊鈕被點擊"); break;
case 2: NSLog(@"確定鈕被點擊"); break;
default: break;
}
}
文字輸入框有七個委派方法,理解它們的呼叫順序對實作「即時驗證」很重要:
// 1. 詢問「能否開始編輯」→ 回傳 NO 則無法聚焦
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
NSLog(@"%s", __FUNCTION__);
return YES;
}
// 2. 已開始編輯(取得焦點後)
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(@"%s", __FUNCTION__);
}
// 3. 詢問「能否結束編輯」(鍵盤是否收起)
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
NSLog(@"%s", __FUNCTION__);
return YES;
}
// 4. 已結束編輯(鍵盤收起後)
- (void)textFieldDidEndEditing:(UITextField *)textField
{
NSLog(@"%s", __FUNCTION__);
}
// 5. 文字即將改變時觸發(僅鍵盤輸入才會觸發,程式設值不會)
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
if (textField.text.length >= 11) {
UIAlertView *alertView =
[[UIAlertView alloc] initWithTitle:@"警告"
message:@"手機號為 11 位"
delegate:self
cancelButtonTitle:@"知道了"
otherButtonTitles:@"好", nil];
[alertView show];
alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
// 截斷多餘輸入
textField.text = [textField.text substringToIndex:10];
}
NSLog(@"%s", __FUNCTION__);
return YES; // 回傳 NO 則本次輸入不生效
}
// 6. 控制清除鈕是否真的清除 → 回傳 NO 則忽略
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
NSLog(@"%s", __FUNCTION__);
return YES;
}
// 7. 點擊鍵盤右下角的 return 時觸發
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSLog(@"%s", __FUNCTION__);
[textField resignFirstResponder]; // 收起鍵盤
return YES;
}
should 開頭的方法回傳 BOOL,是「詢問可否」;Did 開頭的方法回傳 void,是「通知已完成」。這個命名慣例貫穿整個 Cocoa Touch,認住它就能推測任何委派方法的用途。
// 1. 即將失去活躍狀態(將進入後台時觸發)
- (void)applicationWillResignActive:(UIApplication *)application
{
NSLog(@"%s", __FUNCTION__);
// 適合在這裡:暫停進行中的任務、停止計時器、降低 OpenGL ES 幀率
// 遊戲應在此暫停遊戲狀態
}
// 2. 已進入後台(App 被掛起)
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"%s", __FUNCTION__);
// 適合在這裡:釋放共享資源、儲存使用者資料、失效計時器、
// 存下足夠的狀態資訊以便之後被終止時能恢復
}
// 3. 即將進入前台(將要成為活躍狀態)
- (void)applicationWillEnterForeground:(UIApplication *)application
{
NSLog(@"%s", __FUNCTION__);
// 適合在這裡:還原在進入後台時所做的各項調整
}
// 4. 已成為活躍狀態(已進入前台)
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSLog(@"%s", __FUNCTION__);
// 適合在這裡:恢復先前被暫停的任務、必要時刷新 UI
}
// 5. App 即將終止
- (void)applicationWillTerminate:(UIApplication *)application
{
NSLog(@"%s", __FUNCTION__);
// 適合在這裡:儲存資料
}
把順序記起來,除錯時能省下大量時間:
啟動:
application:didFinishLaunchingWithOptions:
→ applicationWillResignActive: (短暫)
→ applicationDidBecomeActive:
按 Home 鍵進入後台:
applicationWillResignActive:
→ applicationDidEnterBackground:
回到前台:
applicationWillEnterForeground:
→ applicationDidBecomeActive:
来电情境:
拒接 → applicationWillResignActive: → applicationDidBecomeActive:
接聽 → applicationDidEnterBackground:
這兩個方法看似都在「離開」,但語意不同,用途也應該區分:
把「暫停動畫」寫在 EnterBackground 而不是 ResignActive,會導致下拉通知中心時動畫繼續跑;反之把「存檔」寫在 ResignActive,則會在每次來電時都做一次昂貴的 I/O。
本文的 UIAlertView 與手動建立 UIWindow 的寫法都屬於早期風格,新專案請注意:
UIAlertController,並以 preferredStyle 區分 alert 與 actionSheet。SceneDelegate,對應關係為:
willConnectToSession ≈ didFinishLaunchingsceneWillResignActive ≈ applicationWillResignActivesceneDidEnterBackground ≈ applicationDidEnterBackgroundsceneWillEnterForeground ≈ applicationWillEnterForegroundsceneDidBecomeActive ≈ applicationDidBecomeActivesceneDidDisconnect ≈ 視圖卸載release 請全部移除。viewDidLoad 中建立,AppDelegate 只負責視窗與根控制器設定。掌握「事件迴圈 → didFinishLaunching → 活躍/後台狀態切換」這條主線,再加上各委派方法的職責分工,就能準確判斷任何時機該做什麼事。