@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self creatUIRectButton];
[self creatImageButton];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(280, 50, 80, 30)];
button.backgroundColor = [UIColor blueColor];
[button setTitle:@"普通按钮" forState:UIControlStateNormal];
[self.view addSubview:button];
}
- (void)creatUIRectButton {
//创建一个普通显示文字的圆角按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//设置位置
button.frame = CGRectMake(100, 100, 80, 40);
/**
* 按钮状态
UIControlStateNormal 正常状态
UIControlStateHighlighted 高亮状态,按下状态
UIControlStateSelected 选中状态
UIControlStateDisabled 失效状态,不可用状态
*/
//设置文字
[button setTitle:@"孩纸别动" forState:UIControlStateNormal];//正常状态
//选中状态
[button setTitle:@"选中状态" forState:UIControlStateSelected];
//高亮状态
[button setTitle:@"按钮按下" forState:UIControlStateHighlighted];
// button.backgroundColor = [UIColor redColor];
//添加事件
/**
*参数1:实现对象
*参数2:当按钮满足参数3事件类型的时候调用
*参数3:事件处理类型函数
UIControlEventTouchDown 当手指触碰到屏幕时触发事件
UIControlEventTouchUpInside 手指离开屏幕且手指的位置在按钮范围内触发事件
UIControlEventTouchUpOutside 手指离开屏幕且手指的位置在按钮范围外触发事件
*
*/
[button addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
//设置按钮的文字风格
//正常状态下的文字
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
//设置所有状态为同一颜色
[button setTintColor:[UIColor greenColor]];
//显示在视图上
[self.view addSubview:button];
}
- (void)pressBtn:(UIButton *) sender{
//更改状态
sender.selected = YES;
NSLog(@"你点了我");
}
- (void)creatImageButton {
//创建一个显示图片的按钮
UIButton *imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
imgBtn.frame = CGRectMake(100, 200, 100, 100);
//设置不同状态下的
[imgBtn setImage:[UIImage imageNamed:@"22EA13461A5A8E53825F70A659E23B91.jpg"] forState:UIControlStateNormal];
[imgBtn setImage:[UIImage imageNamed:@"D9C81341399A18254DDC3F4B118A0697.jpg"] forState:UIControlStateSelected];
[imgBtn setImage:[UIImage imageNamed:@"86F625D78D4269F539EA3DA7C204E923.jpg"] forState:UIControlStateHighlighted];
[imgBtn addTarget:self action:@selector(imgButton:) forControlEvents:UIControlEventTouchUpInside];;
[self.view addSubview:imgBtn];
}
- (void)imgButton:(UIButton *)sender {
sender.selected = YES;
}
UIButton
最新推荐文章于 2024-08-15 18:33:11 发布