初始化
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,100,44);
[self.view addSubview:btn];
typedef NS_ENUM(NSInteger, UIButtonType) {
UIButtonTypeCustom = 0, // no button type 自定义风格
UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0), // standard system button
UIButtonTypeDetailDisclosure,//蓝色小箭头按钮,主要做详细说明
UIButtonTypeInfoLight,//亮色感叹号
UIButtonTypeInfoDark,//暗色感叹号
UIButtonTypeContactAdd,//十字加号按钮
UIButtonTypePlain API_AVAILABLE(tvos(11.0)) API_UNAVAILABLE(ios, watchos), // standard system button without the blurred background view
UIButtonTypeRoundedRect = UIButtonTypeSystem // Deprecated, use UIButtonTypeSystem instead 圆角矩形
};
常用方法和属性
属性和方法 | 解释 |
---|---|
contentEdgeInsets | 内容内距离 |
titleEdgeInsets | 标题内距离 |
reversesTitleShadowWhenHighlighted; | 标题的阴影改变时,按钮是否高亮显示。默认为NO |
imageEdgeInsets; | 图片内边距 |
adjustsImageWhenHighlighted | 按钮高亮的情况下,图像的颜色是否要加深一点。默认是YES |
adjustsImageWhenDisabled | 按钮禁用的情况下,图像的颜色是否要加深一点。默认是YES |
showsTouchWhenHighlighted | 按下按钮是否会发光 默认是NO |
buttonType | button的类型 |
currentTitle | 获取按钮当前标题 |
currentTitleColor | 获取按钮当前标题颜色 |
currentTitleShadowColor | 获取按钮当前阴影标题颜色 |
currentImage | 获取按钮当前按钮内图像 |
currentBackgroundImage | 获取按钮当前标题背景图片 |
currentAttributedTitle | 获取按钮当前标题富文本 |
- (CGRect)backgroundRectForBounds:(CGRect)bounds | 指定背景边界 |
- (CGRect)contentRectForBounds:(CGRect)bounds | 指定内容边界 |
- (CGRect)titleRectForContentRect:(CGRect)contentRect | 指定标题边界 |
- (CGRect)imageRectForContentRect:(CGRect)contentRect | 指定图片边界 |
并不可以通过设置titleLabel属性的文本来设置按钮标题。在苹果官方文档中有描述
[btn setTitle:@"按钮" forState:UIControlStateNormal];//设置标题
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//设置文字颜色
btn.titleLabel.font=[UIFont systemFontOfSize:18];//设置标题字体的大小
[btn setBackgroundColor:[UIColor orangeColor]];//设置背景颜色
[btn setBackgroundImage:[UIImage imageNamed:@"bg.png"] forState:UIControlStateNormal];//设置button的背景图片
[btn setImage:image forState:UIControlStateNormal];//设置前景图片 前景图片必须是镂空图,或者是线条勾勒的图片
[btn setTitleShadowColor:[UIColor purpleColor] forState:UIControlStateNormal];//设置阴影颜色
[btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];//添加按钮事件
btn.enabled=YES;//按钮是否可用
btn.select = YES;//按钮是否选中
btn.showsTouchWhenHighlighted = YES;//设置点击时是否高亮
UIControlState
typedef NS_OPTIONS(NSUInteger, UIControlState) {
UIControlStateNormal = 0, //控件的正常或默认状态 ,即已启用但未选中也未突出显示
UIControlStateHighlighted = 1 << 0, // used when UIControl isHighlighted is set 突出显示控件的状态 俗称高亮
UIControlStateDisabled = 1 << 1, //禁用控件状态
UIControlStateSelected = 1 << 2, // flag usable by app (see below)选择控件的状态
UIControlStateFocused NS_ENUM_AVAILABLE_IOS(9_0) = 1 << 3, // Applicable only when the screen supports focus获得焦点状态
UIControlStateApplication = 0x00FF0000, // additional flags available for application use附加的控制状态标志可供应用程序使用
UIControlStateReserved = 0xFF000000 // flags reserved for internal framework use内部框架使用保留的控制状态
};