其实还是很有必要单独写写平时用的最多的一些单独的控件,今天就先总结下UIButton.还是在之前写的UITableView中讲解,创建了一个FirstViewController让第二行的cell跳转到该视图控制器
1 | - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath |
然后我们在FirstViewController中添加一个UIButton,首页初始化再设置button的frame并设置一下BackgroundColor以方便查看最后在把button``add到当前的视图中.
1 | UIButton *button = [[UIButton alloc] init]; |
运行查看!有一个问题,就是当视图在跳转的过程中感觉不是很流畅有拖?影的感觉,这是因为
self.view在被创建出来的backgroundcolor默认为透明色,因为只要将backgroundcolor设置为非透明色就可以了。如:
1
2 > self.view.backgroundColor = [UIColor whiteColor];
>
首先看下按钮在被点击时有哪些状态
| UIControlStateNormal | 正常状态无任何反应 |
|---|---|
| UIControlStateHighlighted | 标题在点击时显示不点击不显示 |
| UIControlStateDisabled | 禁用状态 |
| UIControlStateSelected | 可以设置被点击后的状态(点赞) |
| UIControlStateFocused | 当屏幕支持聚焦时可用 iOS 9 新属性 |
| UIControlStateApplication | 当用做应用标志时 |
| UIControlStateReserved | 框架预留 无意义 |
setTitle和setImage下状态都是一样的。
前两个状态在平时用的应该是最多的,后面几个具体的用法本人也不是很清楚之后之后如果碰到会补充。☺️
更改字体的颜色:
1 | - (void)setTitleColor:(nullable UIColor *)color forState:(UIControlState)state |
如当被点击时字体颜色更改为红色:
1
2
3 > [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
>
更改button的标题字体
1 | button.titleLabel.font = [UIFont systemFontOfSize:30]; |
点击事件
1 | [button addTarget:self action:@selector(selectButton:) forControlEvents:UIControlEventTouchUpInside]; |
在点击事件中可以实现点击Button后想要实现的效果1
2
3
4
5- (void)selectButton:(UIButton *)sender
{
NSLog(@"%@",sender);
sender.selected = !sender.selected;
}
如改变当前视图的背景颜色:
1
2
3
4
5
6 >- (void)selectButton:(UIButton *)sender
>{
NSLog(@"%@",sender);
self.view.backgroundColor = [UIColor greenColor];
}
>
forControlEvents点击的类型也是有很多种的
| UIControlEventTouchDown | 按下 |
|---|---|
| UIControlEventTouchDownRepeat | 多次按下 |
| UIControlEventTouchDragInside | 保持按下,在按钮及其一定的外围拖动 |
| UIControlEventTouchDragOutside | 保持按下,在按钮外面拖动 |
| UIControlEventTouchDragEnter | DragOutside进入DragInside触发 |
| UIControlEventTouchDragExit | DragInside到DragOutside触发 |
| UIControlEventTouchUpInside | 按钮及其一定外围内松开 |
| UIControlEventTouchUpOutside | 按钮外面松开 |
| UIControlEventTouchCancel | 点击取消 |
- 用的最多的是
UIControlEventTouchUpInside