UIButton控件上自带了一个UILabel和一个UIImageView的子控件,默认情况下图片居左,文字居右,两个子控件作为一个整体可以通过UIButton的contentHorizontalAlignment属性设置其位置,默认为居中。
//水平居中
UIControlContentHorizontalAlignmentCenter = 0,
//水平居左
UIControlContentHorizontalAlignmentLeft = 1,
//水平居右
UIControlContentHorizontalAlignmentRight = 2,
//水平适应
UIControlContentHorizontalAlignmentFill = 3,
本文主要探讨UIButton的imageEdgeInsets和titleEdgeInsets属性的使用,以满足日常开发中的需求。
首先要搞清楚默认状态下UIButton的UILabel和UIImageView的位置:图像和文字都居中显示,imageView在左,label在右,中间没有空隙。
<1>如果要imageView在左边,label在右边,两者都居中显示,imageView离button左边界至少距离为10,label离button右边界距离为至少为10,imageView和label之间的距离为5,具体代码如下:
//button的width:BUTTON_WIDTH
//button上控件imageView的的图片为image
NSString *title = @"label文字";
[button setTitle:title forState:UIControlStateNormal];
[button setImage:image forState:UIControlStateNormal];
CGSize strSize = [title sizeWithFont:button.titleLabel.font];
CGFloat totalLen = strSize.width + 5 + image.size.width;
CGFloat edgeLen = (BUTTON_WIDTH - totalLen) / 2;
if (edgeLen < 10) {
edgeLen = 10;
}
[button setImageEdgeInsets:UIEdgeInsetsMake(0, edgeLen, 0, edgeLen + 5)];
[button setTitleEdgeInsets:UIEdgeInsetsMake(0, edgeLen + 5, 0, edgeLen)];
<2>如果label在左边,imageView在右边,imageView离button右边界为固定值10,label离button左边界也为固定值10,具体代码如下:
NSString *title = @"label文字";
[button setTitle:title forState:UIControlStateNormal];
[button setImage:image forState:UIControlStateNormal];
CGSize strSize = [title sizeWithFont:button.titleLabel.font];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, BUTTON_WIDTH - 10 - image.size.width, 0, (10 - strSize.width))];
CGFloat titleRightInset = BUTTON_WIDTH - 10 - strSize.width;
if (titleRightInset < 10 + image.size.width) {
titleRightInset = 10 + image.size.width;
}
[button setTitleEdgeInsets:UIEdgeInsetsMake(0, (10 - image.size.width), 0, titleRightInset)];
<3>如果imageView在上边,label在下边,imageView与button上边界距离为10,label与button下边界距离为10,具体代码如下:
//button的height:BUTTON_HEIGHT
NSString *title = @"label文字";
[button setTitle:title forState:UIControlStateNormal];
[button setImage:image forState:UIControlStateNormal];
[button setImageEdgeInsets:UIEdgeInsetsMake(10, 0, BUTTON_HEIGHT - 10 - image.size.height , 0)];
[button setTitleEdgeInsets:UIEdgeInsetsMake(BUTTON_HEIGHT - 10 - button.titleLabel.frame.size.height, 0, 10, 0)];
可以看到在竖直方向上,imageView与label独立变化,不用考虑彼此。