单击一个已有的按钮后自动创建一个新的按钮,并为新按钮添加事件,使得单击时弹出提示框。
在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];
}