寫 iOS 的第一個 App,通常是「點一下按鈕,文字就改變」。看似簡單,但其中涵蓋了建立專案、綁定 xib、拖線建立 Action/Outlet、實作事件回呼等一整套基本功。本文以 ButtonFun 為例完整走一遍。
開啟 Xcode,選擇 File → New → Project → Single View Application,按 Next,Product Name 填 ButtonFun,Device 選 iPhone,再選擇存放位置後按 Create。
Xcode 預設使用 Storyboard,這個練習不需要它,可以直接刪掉。接著自行建立 xib:File → New → File,左側選 User Interface,右側選 View,Next 後名稱輸入 ViewController,按 Create。
建立好之後,點開 ViewController.xib,選取左側第一個立方體圖示 File's Owner,在右側第三個分頁中找到 Custom Class,把 class 填為 ViewController。
最後在 ViewController.m 的 viewDidLoad 中載入這個 xib:
- (void)viewDidLoad {
[super viewDidLoad];
UIView *rootView = [[[NSBundle mainBundle] loadNibNamed:@"ViewController"
owner:self
options:nil] lastObject];
self.view = rootView;
}
打開 ViewController.xib,從右下角元件庫把 Button 與 Label 拖進畫面。
接著點選 View → Assistant Editor → Show Assistant Editor,讓左側顯示 xib、右側顯示 ViewController.h。按住 control 鍵把 Button 拖到 .h 檔中,在彈出視窗把 connection 選為 Action,name 填 buttonPressed,按 Connect。再把 Button 拖進 buttonPressed 方法本體,完成事件綁定。
同樣方式把 Label 拖進 .h,這次 connection 選 Outlet,name 填 statusLabel。完成後標頭檔如下:
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
- (IBAction)buttonPressed:(id)sender;
@end
切到 .m 檔,會看到一個空的方法體:
- (IBAction)buttonPressed:(id)sender {
NSString *title = [sender titleForState:UIControlStateNormal];
_statusLabel.text = title;
}
這裡刻意從 sender 取出按鈕自己的 title 再寫進 Label,而不是直接寫死字串——這樣同一個 Action 若日後被多顆按鈕共用,也能各自顯示正確文字。
按下執行、點擊按鈕,Label 文字隨之改變,第一個 App 就完成了。
整個流程其實在建立三種關係:xib 描述「長什麼樣子」,IBOutlet 讓程式碼能「拿到」元件,IBAction 讓元件「呼叫」程式碼。Action 與 Outlet 的差別只在方向:前者由元件指向程式碼,後者由程式碼指向元件。理解這點之後,StoryBoard 與純程式碼寫法都只是同一件事的不同形式。