一句话介绍UIButton:就是手机屏幕按钮。
废话不多说,稍微有一些基础的直接看代码,让你几分钟学会用UIButton:
//创建Button,默认UIButtonTypeCustom样式
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//以下是不同的几种系同样式
typedef enum {
UIButtonTypeCustom = 0,// 自定义样式,无风格
UIButtonTypeRoundedRect,// 白色圆角矩形
UIButtonTypeDetailDisclosure,//详细描述样式
UIButtonTypeInfoLight,//携带小圆圈信息按钮
UIButtonTypeInfoDark,//白色背景,带深色圆圈信息按钮
UIButtonTypeContactAdd,//带蓝色加号号按钮
} UIButtonType;
//Button几种不同状态UIControlState
typedef enum {
UIControlStateNormal = 0,//普通状态
UIControlStateHighlighted = 1 << 0,//点击时的高亮状态
UIControlStateDisabled = 1 << 1,//设置为禁用时的状态
UIControlStateSelected = 1 << 2,//设置为选中时的状态
UIControlStateApplication = 0x00FF0000,//当应用程序标志使用时的状态
UIControlStateReserved = 0xFF000000//为内部框架预留的状态
}UIControlState;
//设置button的坐标和位置大小
btn.frame = CGRectMake(20, 100, 100, 100);
//设置button的默认状态下显示的文字
[btn setTitle:@"124" forState:UIControlStateNormal];
//设置button的默认状态下显示的文字颜色
[btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[btn setTitleShadowColor:[UIColor redColor] forState:UIControlStateNormal];
//设置button的点击状态下显示的文字
[btn setTitle:@"999" forState:UIControlStateHighlighted];
//设置button的点击状态下显示的文字颜色
[btn setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
//设置button的选中状态下显示的文字
[btn setTitle:@"000" forState:UIControlStateSelected];
//设置button的选中状态下显示的文字颜色
[btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
//设置button风格颜色
[btn setTintColor:[UIColor blueColor]];
//设置button中文字大小
btn.titleLabel.font = [UIFont systemFontOfSize:34];
//设置button的背景颜色
btn.backgroundColor = [UIColor greenColor];
//设置button的默认状态下的图片
[btn setImage:[UIImage imageNamed:@"add1"] forState:UIControlStateNormal];
//设置button的点击状态下的图片
[btn setImage:[UIImage imageNamed:@"add"] forState:UIControlStateHighlighted];
//设置button的选中状态下的图片
[btn setImage:[UIImage imageNamed:@"add3"] forState:UIControlStateHighlighted];
//高亮状态下是否修改图片的开关,默认YES。选择NO后,即便是设置了在高亮状态的图片,也不会显示。
btn.adjustsImageWhenHighlighted = YES;
//禁用状态下是否修改图片的开关,默认YES。选择NO后,即便是设置了在高亮状态的图片,也不会显示。
btn.adjustsImageWhenDisabled = YES;
//将Button添加到父视图中
[self.view addSubview: btn];
// backgroundRectForBounds//指定背景边界
// contentRectForBounds//指定内容边界
// titleRectForContentRect//指定文字标题边界
// imageRectForContentRect//指定按钮图像边界
给UIButton添加响应方法,点击Button时,就会调用该方法:
[btn addTarget:self action:@selector(clickMyButtonAction) forControlEvents:UIControlEventTouchDown];
一定要实现这个方法,否则会报错。
-(void)clickMyButtonAction{
NSLog(@"clicking responce");
}
UIButton还有一些其它不常用的属性功能,相信你这些掌握了之后,一定有能力自己尝试使用UIButton更多的功能!