UIButton
UIButton 是 UIControl的子类
UIControl 是 UIView的子类
作用:与用户交互,用户可以点击,并提供响应
核心属性:
- title: 按键上的文字
- image: 按键上的图片
- backgroundImage: 背景图片
- state:状态
高级事件:
-touchUpInside 事件 在button区域内抬起
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
/*
UIButtonTypeCustom 自定义样式
UIButtonTypeSystem 系统样式
UIButtonTypeDetailDisclosure, 圆圈i
UIButtonTypeInfoLight, 圆圈i
UIButtonTypeInfoDark, 圆圈i
UIButtonTypeContactAdd, 圆圈+
*/
//创建Button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
self.button1 = button;
button.frame = CGRectMake(100, 100, 100, 60);
//设置Button上的文字
[button setTitle:@"正常" forState:UIControlStateNormal];
[button setTitle:@"按下" forState:UIControlStateHighlighted];
//设置Button的背景图片
[button setBackgroundImage:[UIImage imageNamed:@"BTN"] forState:UIControlStateNormal];
// [button setBackgroundImage:[UIImage imageNamed:@"BTN2"] forState:UIControlStateHighlighted];
/*选中状态 和 失效状态必须通过代码修改*/
//设置选中时的背景图片
[button setBackgroundImage:[UIImage imageNamed:@"BTN2"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"disable"] forState:UIControlStateDisabled];
//让button失效
// button.enabled = NO;
//设置Button的图片
[button setImage:[UIImage imageNamed:@"Play-btn"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateHighlighted];
//为button添加事件方法
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
//tag 在父视图中的一个标示
button.tag = 100;
[self.view addSubview:button];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
button2.frame = CGRectMake(100, 250, 80, 40);
[button2 setTitle:@"失效" forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
button2.tag = 200;
[self.view addSubview:button2];
}
//两个button 点中都执行 该方法
-(void)buttonClick:(UIButton*)button {
if (button.tag == 100) {
//点中 button1 做的事
button.selected = !button.selected;
return;
}
//点中 button2 做的事
NSString *title = [button.titleLabel.text isEqualToString:@"失效"] ? @"激活" : @"失效";
[button setTitle:title forState:UIControlStateNormal];
self.button1.enabled = [button.titleLabel.text isEqualToString:@"失效"] ? NO : YES;
}