首页 > 代码库 > iOS 动态添加按钮
iOS 动态添加按钮
单击一个已有的按钮后自动创建一个新的按钮,并为新按钮添加事件,使得单击时弹出提示框。
在viewcontroller.h中添加
@property (weak, nonatomic) IBOutletUIButton *addbutton;
为这个按钮添加响应事件addbutton
在viewcontroller.m中添加
- (IBAction)addButton:(id)sender {
//动态添加一个按钮
CGRect frame = CGRectMake(0,0, 300, 50);
UIButton *button = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
button.frame = frame;
[button setTitle:@"新添加的动态按钮"forState: UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
button.tag =2000;
[button addTarget:selfaction:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:button];
}
//这个是新按钮的响应函数
-(IBAction) buttonClicked:(id)sender {
UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:@"提示"
message:@"单击了动态按钮!"
delegate:self
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alertshow];
}
iOS 动态添加按钮