UIButton
1. 功能
- 既能显示文字,又能显示图片(能显示2张图片,背景图片、内容图片)
- 长按高亮的时候可以切换图片\文字
- 直接通过addTarget...方法监听点击
2. 状态
-
normal(普通状态)
- 默认情况(Default)
- 对应的枚举常量:UIControlStateNormal
-
highlighted(高亮状态)
- 按钮被按下去的时候(手指还未松开)
- 对应的枚举常量:UIControlStateHighlighted
-
disabled(失效状态,不可用状态)
- 如果enabled属性为NO,就是处于disable状态,代表按钮不可以被点击
- 对应的枚举常量:UIControlStateDisabled
3. 样式
- 在用代码创建按钮的同时指定按钮样式
- UIButtonTypeCustom:无类型,按钮的内容需要自定义
- UIButtonTypeDetailDisclosure:蓝色小箭头按钮,主要用来做详细说明
- UIButtonTypeInfoLight:亮色感叹号
- UIButtonTypeInfoDark:暗色感叹号
- UIButtonTypeContactAdd:十字加号按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
4. 常见设置
-
(void)setTitle:(NSString *)title forState:(UIControlState)state;
- 设置按钮的文字
-
(void)setTitleColor:(UIColor *)color forState:(UIControlState)state;
- 设置按钮的文字颜色
-
(void)setImage:(UIImage *)image forState:(UIControlState)state;
- 设置按钮内部的小图片
-
(void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;
- 设置按钮的背景图片
-
btn.titleLabel.font = [UIFont systemFontOfSize:13];
- 设置按钮的文字字体(需要拿到按钮内部的label来设置)
-
(NSString *)titleForState:(UIControlState)state;
- 获得按钮的文字
-
(UIColor *)titleColorForState:(UIControlState)state;
- 获得按钮的文字颜色
-
(UIImage *)imageForState:(UIControlState)state;
- 获得按钮内部的小图片
-
(UIImage *)backgroundImageForState:(UIControlState)state;
- 获得按钮的背景图片
5. 常见属性
- enable(是否可用)
//自定义UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];//状态setImage//图片//设置按钮在不同状态下的背景图片(为了保证高亮状态下的图片正常显示,必须设置按钮的type为custom)setBackgroundImage//背景图片setTitle//文字setTitleColor//文字颜色//监听按钮//当UIControlEventTouchUpInside时,调用btn的buttonClick方法[btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
-
因为UIImage和UILabel不是继承UIControl,只有继承UIControl才能通过addTarget来监听事件
-
只能通过enabled = NO达到UIControlStateDisables状态,设置userInterationEnabled = NO,并不能让按钮达到这个状态