IOS开发资料库程序员iOS Developer

iOS 封装好的图文混排(满足各种样式)

2017-04-19  本文已影响395人  一个写代码的文艺姑娘

如果一个界面上就只有这一个功能,总不能再去用个 TableView 来写吧,太麻烦啦😉

如果自己加个大于号,又抵挡不了美工的苛刻,好吧,图文混排满足你;

首先新建一个分类,在. h 文件定义图文混排的样式的枚举

typedef NS_ENUM(NSUInteger, TYButtonEdgeInsetsStyle) {

TYButtonEdgeInsetsStyleTop, // image在上,label在下

TYButtonEdgeInsetsStyleLeft, // image在左,label在右

TYButtonEdgeInsetsStyleBottom, // image在下,label在上

TYButtonEdgeInsetsStyleRight // image在右,label在左

};

然后定义一个设置布局样式的方法,方便调用

/**

*  设置button的titleLabel和imageView的布局样式,及间距

*  @param style titleLabel和imageView的布局样式

*  @param space titleLabel和imageView的间距

*/

- (void)layoutButtonWithEdgeInsetsStyle:(TYButtonEdgeInsetsStyle)style

imageTitleSpace:(CGFloat)space;

.m 文件的实现方法

- (void)layoutButtonWithEdgeInsetsStyle:(TYButtonEdgeInsetsStyle)style

imageTitleSpace:(CGFloat)space

{

// 1. 得到imageView和titleLabel的宽、高

CGFloat imageWidth = self.imageView.frame.size.width;

CGFloat imageHeight = self.imageView.frame.size.height;

CGFloat labelWidth = 0.0;

CGFloat labelHeight = 0.0;

if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {

// 由于iOS8中titleLabel的size为0,用下面的这种设置

labelWidth = self.titleLabel.intrinsicContentSize.width;

labelHeight = self.titleLabel.intrinsicContentSize.height;

} else {

labelWidth = self.titleLabel.frame.size.width;

labelHeight = self.titleLabel.frame.size.height;

}

// 2. 声明全局的imageEdgeInsets和labelEdgeInsets

UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;

UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;

// 3. 根据style和space得到imageEdgeInsets和labelEdgeInsets的值

switch (style) {

case TYButtonEdgeInsetsStyleTop:

{

imageEdgeInsets = UIEdgeInsetsMake(-labelHeight-space/2.0, 0, 0, -labelWidth);

labelEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, -imageHeight-space/2.0, 0);

}

break;

case TYButtonEdgeInsetsStyleLeft:

{

imageEdgeInsets = UIEdgeInsetsMake(0, -space/2.0, 0, space/2.0);

labelEdgeInsets = UIEdgeInsetsMake(0, space/2.0, 0, -space/2.0);

}

break;

case TYButtonEdgeInsetsStyleBottom:

{

imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-space/2.0, -labelWidth);

labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-space/2.0, -imageWidth, 0, 0);

}

break;

case TYButtonEdgeInsetsStyleRight:

{

imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth+space/2.0, 0, -labelWidth-space/2.0);

labelEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-space/2.0, 0, imageWidth+space/2.0);

}

break;

default:

break;

}

// 4. 赋值

self.titleEdgeInsets = labelEdgeInsets;

self.imageEdgeInsets = imageEdgeInsets;

}

最后在需要实现图文混排的地方调用就好啦!😊

[_selectGoodsBtn layoutButtonWithEdgeInsetsStyle:TYButtonEdgeInsetsStyleRight imageTitleSpace:7];

上一篇下一篇

猜你喜欢

热点阅读