UIButton本身已经封装过了,系统给了很多的方法以及属性,但是这样的button依然满足不了 “人类的欲望” ,所以需要自定制,但是自定制button之前我们先把系统的方法回顾一下
// 能够定义的button类型有以下6种,
// typedef enum {
// UIButtonTypeCustom = 0, 自定义风格
// UIButtonTypeRoundedRect, 圆角矩形
// UIButtonTypeDetailDisclosure, 蓝色小箭头按钮,主要做详细说明用
// UIButtonTypeInfoLight, 亮色感叹号
// UIButtonTypeInfoDark, 暗色感叹号
// UIButtonTypeContactAdd, 十字加号按钮
// } UIButtonType;
UIButton * button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button1.frame = CGRectMake(20, 20, 100, 100);
button1.backgroundColor = [UIColor blueColor];
[button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button1 setImage:[UIImage imageNamed:@"2"] forState:UIControlStateNormal];
/* forState: 这个参数的作用是定义按钮的文字或图片在何种状态下才会显现*/
//以下是几种状态
// enum {
// UIControlStateNormal = 0, 常规状态显现
// UIControlStateHighlighted = 1 << 0, 高亮状态显现
// UIControlStateDisabled = 1 << 1, 禁用的状态才会显现
// UIControlStateSelected = 1 << 2, 选中状态
// UIControlStateApplication = 0x00FF0000, 当应用程序标志时
// UIControlStateReserved = 0xFF000000 为内部框架预留,可以不管他
// };
[button1 setTitle:@"点击" forState:UIControlStateNormal];
button1.titleLabel.frame = CGRectMake(0, 0, 30, 20);
/*
* 默认情况下,当按钮高亮的情况下,图像的颜色会被画深一点,如果这下面的这个属性设置为no,
* 那么可以去掉这个功能
*/
button1.adjustsImageWhenHighlighted = NO;
[button1 addTarget:self action:@selector(button1Click) forControlEvents:UIControlEventTouchUpInside];
// UIControlContentHorizontalAlignmentCenter = 0,
// UIControlContentHorizontalAlignmentLeft = 1,
// UIControlContentHorizontalAlignmentRight = 2,
// UIControlContentHorizontalAlignmentFill = 3,填充对齐
//设置UIButton的标题对齐方式
[button1 setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];//左对齐
//设置相对于原来的位置移动了多少 向下(负向上) 往右 向上 往左
button1.imageEdgeInsets = UIEdgeInsetsMake(0,25,20,0);
button1.titleEdgeInsets = UIEdgeInsetsMake(40, -15, 0, 0);
[self.view addSubview:button1];
由于方法太多放到另外一个里面
UIButton * button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button2 setTitle:@"button2" forState:UIControlStateNormal];
// button2.imageView.image = [UIImage imageNamed:@"1"];
[button2 setImage:[UIImage imageNamed:@"2"] forState:UIControlStateNormal];
button2.frame = CGRectMake(150, 20, 100, 100);
button2.backgroundColor = [UIColor yellowColor];
button2.adjustsImageWhenDisabled = YES;//图片是否禁用
button2.adjustsImageWhenHighlighted = YES;//图片是否高亮
button2.showsTouchWhenHighlighted = NO;//button是否高亮
button2.reversesTitleShadowWhenHighlighted = NO;
// UIImage * image = button2.currentImage;//只读当前button上的image
// NSString * title = button2.currentTitle;//只读
//currentTitleColor 文字颜色只读
//currentTitleShadowColor 文字阴影颜色只读
[button2 setTitleShadowColor:[UIColor redColor] forState:UIControlStateNormal];
[self.view addSubview:button2];
button2.titleShadowOffset = CGSizeMake(1, 0);
button2.lineBreakMode = NSLineBreakByWordWrapping; //换行
button2.font = [UIFont systemFontOfSize:20];
CGRect rect = [button2 backgroundRectForBounds:CGRectMake(0, 0, 100, 100)];
NSLog(@"%f",rect.size.width);
系统方法就是这些了