有時候按鈕數量在執行期才確定,或者要依使用者操作即時補上一顆,這時就必須在程式碼中動態建立 UIButton。本例示範:點一下「添加 button」,畫面上多出一顆按鈕,再點它會跳出提示框。
從物件庫拖一個 button 到畫面,標題設為「添加 button」。
按住 Ctrl 拖到 addbuttonViewController.m 的空白處產生 IBAction,補上實作:
- (IBAction)addButton:(id)sender {
CGRect frame = CGRectMake(90, 200, 200, 60);
UIButton *someAddButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
someAddButton.backgroundColor = [UIColor clearColor];
[someAddButton setTitle:@"動態添加一個按鈕!" forState:UIControlStateNormal];
someAddButton.frame = frame;
[someAddButton addTarget:self
action:@selector(someButtonClicked)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:someAddButton];
}
三個關鍵動作:用 buttonWithType: 取得按鈕實例、用 setTitle:forState: 設定標題(務必指定 UIControlStateNormal,否則一般狀態下看不到文字)、用 addTarget:action:forControlEvents: 綁定點擊事件,最後 addSubview: 把它放進畫面。frame 決定位置與大小,這裡刻意拉寬以便看清標題。
-(void) someButtonClicked {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"您點擊了動態按鈕!"
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
}
執行後畫面上只有原本那顆「添加 button」;點它之後,新的圓角按鈕出現在 (90, 200) 的位置;再點新按鈕,便彈出標題為「提示」的警告框。
動態建立的元件若沒有持有引用,後續要修改或移除會很麻煩,實務上通常會用 NSMutableArray 收集起來,或存成 property。若同一個 action 被多顆按鈕共用,可把 sender 轉型為 UIButton 再比對,即可分辨來源。另外,UIAlertView 在 iOS 8 之後已廢棄,新專案請改用 UIAlertController;而 iOS 9 起也建議以 UIStackView 搭配 Auto Layout 取代手動算 frame,畫面在不同尺寸螢幕上才不會跑位。