02-动态创建按钮
在ViewController.m文件中:
viewDidLoad:被系统调用,调用时机:加载View Controll完毕之后
1 // 这是控制器的一个方法:当控制器的view创建完毕的时候调用一次 2 - (void)viewDidLoad { 3 [super viewDidLoad]; 4 // Do any additional setup after loading the view, typically from a nib. 5 6 // 1.创建按钮 7 // 1.1创建 8 UIButton *btn = [[UIButton alloc] init]; 9 NSLog(@"btn -- %p", btn); 10 11 // 1.2设置按钮的尺寸和位置 12 btn.frame = CGRectMake(0, 0, 100, 100); 13 14 // 1.3设置按钮普通状态下的属性 15 // 1.3.1设置背景图片 16 UIImage *normal = [UIImage imageNamed:@"btn_01.png"]; 17 [btn setBackgroundImage:normal forState:UIControlStateNormal]; 18 19 // 1.3.2设置文字 20 [btn setTitle:@"点我咯" forState:UIControlStateNormal]; 21 22 // 1.3.3设置文字颜色 23 [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; 24 25 // 1.4设置按钮高亮状态下的属性 26 // 1.4.1设置背景图片 27 UIImage *high = [UIImage imageNamed:@"btn_02.png"]; 28 [btn setBackgroundImage:high forState:UIControlStateHighlighted]; 29 30 // 1.4.2设置文字 31 [btn setTitle:@"摸我干啥" forState:UIControlStateHighlighted]; 32 33 // 1.4.3设置文字颜色 34 [btn setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted]; 35 36 // 1.5监听按钮点击 37 [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside]; 38 39 // 1.6增加到view中 40 [self.view addSubview:btn]; 41 42 UITextField *txt = [[UITextField alloc] init]; 43 txt.frame = CGRectMake(100, 100, 100, 50); 44 CGFloat centerX = self.view.frame.size.width*0.5; 45 CGFloat centerY = self.view.frame.size.height*0.5; 46 txt.center = CGPointMake(centerX, centerY); 47 txt.backgroundColor = [UIColor redColor]; 48 [txt setText:@"默认文本值"]; 49 [txt setFont:[UIFont boldSystemFontOfSize:20]]; 50 51 [self.view addSubview:txt]; 52 } 53 54 - (void)didReceiveMemoryWarning { 55 [super didReceiveMemoryWarning]; 56 // Dispose of any resources that can be recreated. 57 } 58 59 - (void)btnClick:(UIButton *)btn 60 { 61 NSLog(@"btnClick -- %p", btn); 62 63 }
1.添加控件到控制器的view
[self.view addSubView:子控件];
2.监听按钮点击
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];