#pragma mark 控制器的view加载完毕的时候调用 //一般在这里进行界面的初始化 - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"%s","ddffg"); //添加 //创建控件 UIButton *btn=[[UIButton alloc]init]; //添加控件 [self.view addSubview:btn]; //设置控件的frame btn.frame=CGRectMake(100, 200, 200, 200); //设置背景色 btn.backgroundColor=[UIColor redColor]; //设置背景图片 UIImage *image=[UIImage imageNamed:@"a18.jpg"]; [btn setBackgroundImage:image forState:UIControlStateNormal]; UIImage *image2=[UIImage imageNamed:@"a1.jpg"]; [btn setBackgroundImage:image2 forState:UIControlStateHighlighted]; //设置文字 [btn setTitle:@"立海" forState:UIControlStateNormal]; [btn setTitle:@"娃娃" forState:UIControlStateHighlighted]; //设置文字颜色 [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [btn setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted]; //监听按钮点击,事件名:btnClick [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside]; //addBtn按钮同样监听 事件史:btnClick UIButton *addBtn=[UIButton buttonWithType:UIButtonTypeContactAdd]; [addBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside]; //设置按钮在界面的位置 addBtn.center=CGPointMake(250, 250); // //添加控件到界面 [self.view addSubview:addBtn]; } -(void) btnClick:(UIButton *)click { NSLog(@"%@ 按钮事件触发了!",click); }