Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

iOS 開發實作:動態產生 UIButton 並監聽 UIAlertView 點擊

有時候按鈕數量在執行期才確定,或者要依使用者操作即時補上一顆,這時就必須在程式碼中動態建立 UIButton。本例示範:點一下「添加 button」,畫面上多出一顆按鈕,再點它會跳出提示框。

步驟一:在 xib 放一顆觸發用按鈕

從物件庫拖一個 button 到畫面,標題設為「添加 button」。

步驟二:建立 Action 並填入程式碼

按住 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,畫面在不同尺寸螢幕上才不會跑位。

Copyright © Linux教程網 All Rights Reserved