iOS开发教程之动态添加Button和监听UIAlertView按钮


一、动态添加Button

动态添加Button的效果就是点击之后,生成一个按钮,并为按钮添加点击的方法。

1、在xib文件上拖拽添加一个button,标题为:添加button。

2、按住ctrl键拖拽到addbuttonViewController.m文件空白处,生成IBAction,填充代码后如下:

  1. - (IBAction)addButton:(id)sender {  
  2.     CGRect frame = CGRectMake(90, 200, 200, 60);  
  3.     UIButton *someAddButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  4.     someAddButton.backgroundColor = [UIColor clearColor];  
  5.     [someAddButton setTitle:@"动态添加一个按钮!" forState:UIControlStateNormal];  
  6.     someAddButton.frame = frame;  
  7.     [someAddButton addTarget:self action:@selector(someButtonClicked) forControlEvents:UIControlEventTouchUpInside];  
  8.     [self.view addSubview:someAddButton];  

3、动态生成的button点击事件方法:

生成的button点击弹出提示框。

  1. -(void) someButtonClicked{    
  2.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"   
  3.                                                     message:@"您点击了动态按钮!"     
  4.                                                    delegate:self     
  5.                                           cancelButtonTitle:@"确定"    
  6.                                           otherButtonTitles:nil];    
  7.     [alert show];  
  8. }  

4、编译运行效果 图1 2 3:

图1:

点击按钮后

图2:

图3:

  • 1
  • 2
  • 3
  • 下一页

相关内容