首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

动态增添Button和监听UIAlertView按钮

2013-01-23 
动态添加Button和监听UIAlertView按钮一、动态添加Button[img][/img]动态添加Button的效果就是点击之后,生

动态添加Button和监听UIAlertView按钮
一、动态添加Button

[img]

[/img]

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

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

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

谨记,并注意:fram前面没有 *
哎,犯了好几次这样的小错   我靠,fuck;

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


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

生成的button点击弹出提示框。
-(void) someButtonClicked{      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"                                                     message:@"您点击了动态按钮!"                                                      delegate:self                                             cancelButtonTitle:@"确定"                                            otherButtonTitles:nil];      [alert show];}




二、监听UIAlertView

1、在上面的代码基础上,在addbuttonViewController.h文件添加委托
#import <UIKit/UIKit.h>@interface addbuttonViewController : UIViewController<UIAlertViewDelegate>- (IBAction)addButton:(id)sender;@end


2、在AlertView中多添加两个按钮
-(void) someButtonClicked{      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"                                                     message:@"您点击了动态按钮!"                                                      delegate:self                                             cancelButtonTitle:@"确定"                                            otherButtonTitles:@"取消",@"第三项",nil];      [alert show];}


3、在对应的.m文件中实现委托中的方法

监听你点击了那个按钮
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{    NSLog(@"buttonIndex:%d", buttonIndex);}


点击AlertView中弹出的三个按钮打印的结果:
2012-06-14 16:53:18.516 DynamicAddButton[5645:f803] buttonIndex:12012-06-14 16:53:23.652 DynamicAddButton[5645:f803] buttonIndex:22012-06-14 16:53:25.701 DynamicAddButton[5645:f803] buttonIndex:02012-06-14 16:53:39.900 DynamicAddButton[5645:f803] buttonIndex:1

热点排行