UIButton是一个标准的UIControl控件
一、创建
两种方法:
1. 常规的 initWithFrame
UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, 80, 44)];
对代码创建View(UIControl继承自UIView,所以也是view)不甚了解的请参看:《有关View的几个基础知识点》
2. UIButton 的一个类方法(也可以说是静态方法)buttonWithType
UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
风格有如下
typedef enum { UIButtonTypeCustom = 0, // no button type 自定义,无风格 UIButtonTypeRoundedRect, // rounded rect, flat white button, like in address card 白色圆角矩形,类似偏好设置表格单元或者地址簿卡片 UIButtonTypeDetailDisclosure,//蓝色的披露按钮,可放在任何文字旁 UIButtonTypeInfoLight,//微件(widget)使用的小圆圈信息按钮,可以放在任何文字旁 UIButtonTypeInfoDark,//白色背景下使用的深色圆圈信息按钮 UIButtonTypeContactAdd,//蓝色加号(+)按钮,可以放在任何文字旁 } UIButtonType; |
二、设置属性
1.Frame属性
第2种方法创建按钮后你可以给按钮的frame属性赋值,用一个CGRect结构设置他的位置和大小
CGRect btn2Frame = CGRectMake(10.0, 10.0, 60.0, 44.0);
btn2.frame =btn2Frame;
2. title属性
对于任何特定状态下的按钮,都可以设定该按钮该状态下的按钮标题。用setTitle 方法 设置即可:
[btn1 setTitle:@"BTN1" forState:UIControlStateNormal];
你也可以为按钮的某一状态设置为图。用 setImage 即可:
[btn2 setImage:[UIImage imageNamed:@"pic"] forState:UIControlStateNormal];
此外,你还可以为每种按钮状态设置标题的颜色和阴影,以及按钮的背景。方法 setTitleColor 和 setTitleShadowColor 都需要一个UIColor对象做参数:
[btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];//设置标题颜色
[btn1 setTitleShadowColor:[UIColor grayColor] forState:UIControlStateNormal ];//阴影
[btn1 setBackgroundImage:[UIImage imageNamed:@"PIC"] forState:UIControlStateHighlighted];//背景图像
上面几个方法都提到 共同的参数 forState . 这个参数决定了标题、图像或其他属性将在何种状态下显现。你可以编程令按钮在那个状态变化
enum { UIControlStateNormal = 0, //常态 UIControlStateHighlighted = 1 << 0, // used when UIControl isHighlighted is set 高亮 UIControlStateDisabled = 1 << 1, //禁用 UIControlStateSelected = 1 << 2, // flag usable by app (see below) 选中 UIControlStateApplication = 0x00FF0000, // additional flags available for application use 当应用程序标志使用时 UIControlStateReserved = 0xFF000000 // flags reserved for internal framework use 为内部框架预留的 }; typedef NSUInteger UIControlState; |
你只要掌握前四种状态就好了。