CGRect frame = CGRectMake(10.0f, 10.0f, 120.0f, 50.0f);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];//初始化一个UIButton
button.frame = frame;//设置button的大小和位置
[button setTitle:@"title"forState:UIControlStateNormal];//设置button正常状态下的文字
button.tag = 2000; //区分同种控件的标记 这个和android 控件里面的getId一样 在事件里面用来区分是那个控件的事件
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];//对应处理的事件方法 和那个事件
[self.view addSubview:button];//把button添加到view里面显示
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
CGRect frame2 = CGRectMake(100, 100, 100, 60);
button2.frame=frame2;
[button2 setTitle:@"test"forState:UIControlStateNormal];
button2.tag = 2001;
[button2 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];//selector后面的方法后一定不要忘了要加个冒号 ,因为定义的buttonClicked方式后面是带了类型为id的参数
[ self . view addSubview :button2];-(IBAction)buttonClicked:(UIButton*)sender//事件处理的方法 sender对应的按钮
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"title"message:@"message"delegate:self cancelButtonTitle:@"确定"otherButtonTitles:@"otherbuttontitles", nil];//提示框 delegate 对应的是事件处理在.h 文件加上UIViewController<UIAlertViewDelegate>
switch ([sender tag]) {
case 2000:
[alert show];
break;
case 2001:
[sender setTitle:@"sender" forState:UIControlStateNormal];
break;
};
NSLog(@"button Clicked!");}
-(void) alertView:(UIAlertView *)alertview clickedButtonAtIndex:(NSInteger)buttonIndex{//alertView 事件处理的方法 buttonIndex 对应buton的下标
NSLog(@"%@=====%d",alertview.title,buttonIndex);
}