您的位置:首页 > 产品设计 > UI/UE

22.UIButton的标题和图片位置的调整/Image和BackgroundImage

2016-02-23 17:11 405 查看
按钮(UIButton)的标题(tittle)和按钮的图片(image)如何设调整位置和间距?本文还涉及到setImage和setBackgroundImage的区别。

1.通过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;
//




2.通过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)];,效果如图:



3.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 这个方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: