需求很單純:點擊一個既有的按鈕後,自動建立一個新按鈕,並為新按鈕加上事件,點下去時彈出提示框。
首先在 ViewController.h 中宣告既有的那顆按鈕:
@property (weak, nonatomic) IBOutlet UIButton *addbutton;
接著為它加上回應事件 addButton。
然後在 ViewController.m 中實作:
- (IBAction)addButton:(id)sender {
// 動態添加一個按鈕
CGRect frame = CGRectMake(0, 0, 300, 50);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
[button setTitle:@"新添加的動態按鈕" forState: UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
button.tag = 2000;
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
// 這個是新按鈕的回應函式
-(IBAction) buttonClicked:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"單擊了動態按鈕!"
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alert show];
}
關鍵就三件事:用 buttonWithType: 建立按鈕、設定 frame 與 tag(方便之後反查或移除),再用 addTarget:action:forControlEvents: 綁定事件,最後 addSubview: 放進視圖階層。UIAlertView 在 iOS 8 之後已被 UIAlertController 取代,新專案請改用後者。