按钮(UIButton)的标题(tittle)和按钮的图片(image)如何设调整位置和间距? 还有关于setImage和setBackgroundImage的区别。
调整标题的水平和垂直对齐方式
通过contentHorizontalAlignment/contentVerticalAlignment来调整title的位置。
在 UIControl.h 中有如下参数:
@property(nonatomic) UIControlContentVerticalAlignment contentVerticalAlignment; // how to position content vertically inside control. default is center
@property(nonatomic) UIControlContentHorizontalAlignment contentHorizontalAlignment; // how to position content hozontally inside control. default is center
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(50, 50, 100, 50);
[button setTitle:@"title" forState:UIControlStateNormal];
button.backgroundColor = [UIColor cyanColor];
[self.view addSubview:button];
//水平方向布局
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//垂直方向布局
button.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
//
调整标题和图片的位置
通过setTitleEdgeInsets/setImageEdgeInsets来调整title位置及图片(image)位置。
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(50, 50, 150, 50);
button.backgroundColor = [UIColor greenColor];
[self.view addSubview:button];
[button setImage:[UIImage imageNamed:@"11.png"] forState:UIControlStateNormal];
[button setTitle:@"按钮" forState:UIControlStateNormal];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 50)];
[button setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
//
效果图:
通过效果图可以发现 image 和 title 是左右分布的, 但若写成上下分布:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(50, 50, 50, 150);
button.backgroundColor = [UIColor greenColor];
[self.view addSubview:button];
[button setImage:[UIImage imageNamed:@"11.png"] forState:UIControlStateNormal];
[button setTitle:@"按钮" forState:UIControlStateNormal];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 70, 0)];
[button setTitleEdgeInsets:UIEdgeInsetsMake(70, 0, 0, 0)];
//
效果图:
可见 title 显示不出来, 但通过修改发现当 button 宽度修改为100时,可以显示出来如图:
所以,要解决这个问题需要将 title 的 EdgeInsets 的 left改为负距离便可。将上面代码中改为[button setTitleEdgeInsets:UIEdgeInsetsMake(70, -80, 0, 0)];,效果如图:
setImage和setBackgroundImage的区别
setBackgroundImage:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(50, 50, 100, 150);
button.backgroundColor = [UIColor greenColor];
[self.view addSubview:button];
[button setBackgroundImage:[UIImage imageNamed:@"11.png"] forState:UIControlStateNormal];
[button setTitle:@"按钮" forState:UIControlStateNormal];
[button setTitleEdgeInsets:UIEdgeInsetsMake(70, 0, 0, 0)];
效果图:
经过上面测试,发现用setImage方法设置的图片,图片不会随着按钮的放大而放大,图片始终是原始图片尺寸,而用setBackgroundImage方法设置的图片,图片会随着按钮的变大而拉伸变大。故setBackgroundImage没有设置 EdgeInsets 这个方法。