UIButton
什么是按钮?
一般情况下点击某个控件后,能做出相应反应的我们都把它叫作按钮
它是一个非常重要的UI控件,后面基本天天与它打交道
按钮的功能有很多,它既能显示图片,也能显示文字,还能自己调整内部图片的文字位置
按钮的状态
普通状态(normal)
- 对应的枚举常量为:UIControlStateNormal
- 默认状态
高亮状态(highlighted)
- 对应的枚举常量为UIControlStateHighlighted
- 当按钮被点下去的时候
失效状态(disabled)
- 对应的枚举常量为UIControlStateDisabled
- 当设置enabled属性为NO的时候,表示按钮不能点击
选中状态(selected)
- 对应的枚举常量为UIControlStateSelected
按钮的背景图片
- storyboard中设置
- 在下面可以选择按钮类型,按钮状态,按钮显示的文字,按钮的字体,按钮的背景图片等
- 在下面可以选择按钮类型,按钮状态,按钮显示的文字,按钮的字体,按钮的背景图片等
- 代码设置
按钮的样式
UIButtonTypeCustom(最常用,自己定义用)
UIButtonTypeSystem (系统自带,不是很好用)
UIButtonTypeDetailDisclosure(不常用,蓝色的披露按钮,可放在任何文字旁)
UIButtonTypeInfoLight(不常用,小圆圈信息按钮)
UIButtonTypeInfoDark(不常用,白色背景下使用的深色圆圈信息按钮)
UIButtonTypeContactAdd,(调程序懒得创建一个的时候用一下,不常用,显示一个加号)
按钮的常见设置(使用步骤,详情见后面代码部分)
- 创建按钮
- 设置位置和尺寸
- 设置按钮文字
- 设置按钮文字颜色
- 设置按钮内部小图片
- 设置按钮的背景图片
- 为按钮添加监听
添加到父控件中显示
——–获取———
- (NSString *)titleForState:(UIControlState)state;
获得按钮的文字- (UIColor *)titleColorForState:(UIControlState)state;
获得按钮的文字颜色- (UIImage *)imageForState:(UIControlState)state;
获得按钮内部的小图片- (UIImage *)backgroundImageForState:(UIControlState)state;
获得按钮的背景图片
代码部分
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//第一种创建,创建的时候指定它的类型为Custom,一般都选这个,它表示要自定义它的类型
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
//这个是系统自己的button,一般少用
UIButton *systemButton = [UIButton buttonWithType:UIButtonTypeSystem];
//这种方式也是常用的
UIButton *myButton1 = [[UIButton alloc] init];
//设置按钮的位置和尺寸
myButton.frame = CGRectMake(130, 100, 64, 64);
myButton1.frame =CGRectMake(130, 200, 64, 64);
//设置按钮文字
[myButton setTitle:@"按钮" forState:UIControlStateNormal];
//设置按钮文字颜色
[myButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//设置按钮内部小图片
[myButton1 setImage:[UIImage imageNamed:@"button1"] forState:UIControlStateNormal];
//设置按钮背景图片
// [myButton setBackgroundImage:[UIImage imageNamed:@"button1" ] forState:UIControlStateNormal];
//
/**
* 监听按钮的点击
*
* @param running 当点击的时候执行这个方法
*/
[myButton1 addTarget:self action:@selector(running) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:myButton];
[self.view addSubview:myButton1];
}
- (void)running
{
NSLog(@"%s",__func__);
}
@end
执行效果
- 添加的3个按钮
监听按钮的点击事件