UIButton
UIButton是一个常用到的UI控件, 俗称”按钮”。
一般情况下,点击某个控件后,会做出相应反应的都是按钮
按钮的功能比较多,既能显示文字,又能显示图片,还能随时调整内部图片和文字的位置
作用:监听用户的点击事件,在用户点击后做出响应
这个是Button
这个也是Button
那么,我们废话不多说,赶紧上代码
首先,我么需要写一个方法创建一个文字按钮,
-(void)creatUIRectBUtton{
// 创建一个普通显示文字的按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 设置位置
button.frame = CGRectMake(100, 100, 80, 40);
// 设置文字
/**
* UIControlStateNormal 正常状态
UIControlStateSelected 选中状态
UIControlStateHighlighted 高亮状态,按下状态
UIControlStateDisabled 失效状态,不可用状态
*/
[button setTitle:@"孩纸别动" forState:UIControlStateNormal];
// 选中状态
[button setTitle:@"选中按钮" forState:UIControlStateSelected];
// 高亮
[button setTitle:@"按钮按下" forState:UIControlStateHighlighted];
// 设置背景色
// button.backgroundColor = [UIColor redColor];
button.titleLabel.font = [UIFont systemFontOfSize:20.0];
#pragma mark 添加事件
/**
* p1 : 谁来实现这个函数,实现者对象就是"谁",一般self
* p2:@selector(<#selector#>) 函数对象,当按钮满足p3事件类型的时候调用
* p3:(UIControlEvents)事件处理类型函数
*
UIControlEventTouchDown :当我们的手指只要触碰到屏幕时触发事件
UIControlEventTouchUpInside 当我们的手指离开屏幕且手指的位置在按钮的范围内触发事件
UIControlEventTouchUpOutside 当我们的手指离开屏幕且手指的位置在按钮的范围外触发事件
*
*/
[button addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
// 设置按钮的文字风格
// 正常状态下的文字
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
// 高亮状态下的文字
[button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[button setTintColor:[UIColor blackColor]];
// 显示在视图上
[self.view addSubview:button];
}
实现一下button的点击事件方法
-(void)pressBtn:(UIButton *)sender{
// 更改状态
sender.selected =! sender.selected;
NSLog(@"你点了我");
}
到这里我们需要在viewDidLoad调用一下我们刚刚写的那个创建普通文字按钮的方法,让他显示在我们的视图上
1.普通状态下的按钮
2.高亮状态下的按钮
3.选中状态下的按钮
文章开头说过按钮可以显示文字和图片,那么普碳显示文字的按钮我们做了,现在我们再来做一个显示图片的按钮
1,首先我们需要拖拽三张图片进我们的工程里面
2.同样的我们需要写一个方法创建一个显示图片的按钮
-(void)creatImageButton{
// 创建一个显示图片的按钮
UIButton *imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
imgBtn.frame = CGRectMake(100, 300, 100, 100);
// 设置不同状态下的图片
// p1 显示图片的对象
// p2 控件的状态
// 正常状态
[imgBtn setImage:[UIImage imageNamed:@"btn01"] forState:UIControlStateNormal];
// 选中状态
[imgBtn setImage:[UIImage imageNamed:@"btn03"] forState:UIControlStateSelected];
// 高亮
[imgBtn setImage:[UIImage imageNamed:@"btn02"] forState:UIControlStateHighlighted];
#pragma mark 添加点击事件
[imgBtn addTarget:self action:@selector(imgButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:imgBtn];
}
3.实现一下按钮的点击事件
-(void)imgButton:(UIButton *)sender{
sender.selected = ! sender.selected;
}
4,最后在viewDidLoad调用一下我们刚刚创建显示图片的按钮
“`
(void)viewDidLoad {
[super viewDidLoad][self creatImageButton];
}
模拟器运行效果如下
普通状态下显示图片的按钮
高亮状态下的按钮
选中状态下的按钮