單擊一個已有的按鈕後自動創建一個新的按鈕,並為新按鈕添加事件,使得單擊時彈出提示框。
在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];
}