UIButton 幾乎是所有 App 都會用到的互動元件。它看起來簡單,實際上要處理的細節不少:外觀型別、文字與圖片的狀態、高亮時的視覺回饋,以及最後的事件綁定。下面用一段完整的程式碼把這些環節串起來說明。
// 建立一個圓角矩形樣式的按鈕
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 可指定的 button 型別共有 6 種
// typedef enum {
// UIButtonTypeCustom = 0, 自訂樣式
// UIButtonTypeRoundedRect, 圓角矩形
// UIButtonTypeDetailDisclosure, 藍色小箭頭,常用於「看更多」
// UIButtonTypeInfoLight, 亮色資訊圖示
// UIButtonTypeInfoDark, 暗色資訊圖示
// UIButtonTypeContactAdd 十字加號
// } UIButtonType;
// 指定按鈕在畫面上的位置與大小
button1.frame = CGRectMake(20, 20, 280, 20);
// 背景設為透明
button1.backgroundColor = [UIColor clearColor];
// 設定填充圖片(暫不啟用)
// [button1 setImage:[UIImage imageNamed:@"btng.png"] forState:UIControlStateNormal];
// 設定標題文字
[button1 setTitle:@"點擊" forState:UIControlStateNormal];
// forState: 決定文字或圖片要在哪一種狀態下才顯示
// enum {
// UIControlStateNormal = 0, 一般狀態
// UIControlStateHighlighted = 1 << 0, 高亮(手指按下)
// UIControlStateDisabled = 1 << 1, 停用狀態
// UIControlStateSelected = 1 << 2, 選中狀態
// UIControlStateApplication = 0x00FF0000, 供應用程式自訂使用
// UIControlStateReserved = 0xFF000000 系統保留,可忽略
// };
// 預設情況下按鈕高亮時圖片會被加深,設為 NO 可關閉此行為
button1.adjustsImageWhenHighlighted = NO;
// 同理,停用時圖片也會被加深,設為 NO 取消
button1.adjustsImageWhenDisabled = NO;
// 設為 YES 時,按下按鈕會顯示一輪光暈
button1.showsTouchWhenHighlighted = YES;
// 綁定事件:手指按下後離開畫面時觸發,等同 Web 的 click
// addTarget:self 表示 action 方法寫在當前類別中,也可傳入其他類別
[button1 addTarget:self
action:@selector(butClick:)
forControlEvents:UIControlEventTouchUpInside];
// 把按鈕加入畫面
[self.view addSubview:button1];
型別會決定預設外觀。UIButtonTypeRoundedRect 自帶圓角與灰階漸層,而 UIButtonTypeCustom 則完全交給你自己畫。若專案有設計稿,通常直接用 Custom 搭配 setBackgroundImage:forState: 比較可控。
狀態是關鍵字。setTitle:forState: 與 setImage:forState: 都必須指定狀態,否則切換時會出現文字消失或圖片不見的狀況。常見搭配是同時準備 Normal 與 Highlighted 兩張圖,做出按下回饋。
事件種類很多。TouchUpInside 是最常用的一種,其他還有 TouchDown、TouchDragEnter、TouchDragExit 等,適合用來實作拖曳式操作或長按效果。