思路:
1驶忌、獲取UIButton的子控件imageView和titleLabel的size
2、聲明兩個UIEdgeInsets變量imageEdgeInsets和labelEdgeInsets
3笑跛、根據(jù)style(自定義的枚舉)和space設(shè)置imageEdgeInsets和labelEdgeInsets的值
4付魔、最后將imageEdgeInsets和labelEdgeInsets的值賦值給UIButton的titleEdgeInsets 和imageEdgeInsets
效果圖如下:
typedef NS_ENUM(NSUInteger, CLButtonEdgeInsetsTitleStyle) {
CLButtonEdgeInsetsStyleTitleTop, // title在上
CLButtonEdgeInsetsStyleTitleLeft, // title在左
CLButtonEdgeInsetsStyleTitleBottom, // title在下
CLButtonEdgeInsetsStyleTitleRight // title在右
};
自定義的枚舉樣式
/**
設(shè)置button的titleLabel和imageView的布局樣式,及間距
@param style titleLabel和imageView的布局樣式
@param space titleLabel和imageView的間距
*/
- (void)layoutButtonWithEdgeInsetsStyle:(CLButtonEdgeInsetsTitleStyle)style
imageTitleSpace:(CGFloat)space
{
// 1. 得到imageView和titleLabel的size
CGSize titleSize = self.titleLabel.intrinsicContentSize;
CGSize imageSize = self.imageView.bounds.size;
// 2. 聲明全局的imageEdgeInsets和labelEdgeInsets
UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;
UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;
// 3. 根據(jù)style和space設(shè)置imageEdgeInsets和labelEdgeInsets的值
switch (style) {
case CLButtonEdgeInsetsStyleTitleTop:
{
labelEdgeInsets = UIEdgeInsetsMake(0,-(imageSize.width), imageSize.height + space * 0.5, 0);
imageEdgeInsets = UIEdgeInsetsMake(titleSize.height + space * 0.5, 0, 0, -(titleSize.width));
}
break;
case CLButtonEdgeInsetsStyleTitleLeft:
{
imageEdgeInsets = UIEdgeInsetsMake(0, titleSize.width , 0, - titleSize.width - space * 0.5);
labelEdgeInsets = UIEdgeInsetsMake(0, - imageSize.width, 0, imageSize.width + space * 0.5);
}
break;
case CLButtonEdgeInsetsStyleTitleBottom:
{
imageEdgeInsets = UIEdgeInsetsMake(0,0, titleSize.height + space * 0.5, -(titleSize.width));
labelEdgeInsets = UIEdgeInsetsMake(imageSize.height + space * 0.5, -(imageSize.width), 0, 0);
}
break;
case CLButtonEdgeInsetsStyleTitleRight:
{
imageEdgeInsets = UIEdgeInsetsMake(0, self.imageEdgeInsets.left - space / 2, 0, 0);
labelEdgeInsets = UIEdgeInsetsMake(0, self.titleEdgeInsets.left + space / 2, 0, 0);
}
break;
default:
break;
}
// 4. 賦值
self.titleEdgeInsets = labelEdgeInsets;
self.imageEdgeInsets = imageEdgeInsets;
}
注意:
1飞蹂、使用的時候要先設(shè)置Button的圖片和title几苍,然后在調(diào)用- (void)layoutButtonWithEdgeInsetsStyle:(CLButtonEdgeInsetsTitleStyle)style
imageTitleSpace:(CGFloat)space;方法。
2陈哑、獲取UIButton的子控件imageView和titleLabel的size所用方法不一樣妻坝。具體原因不是很清楚伸眶。