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

IOS总结实现UIButton的图文混排 同时显示文字和图片

2015-05-28 22:44 741 查看
默认情况下,在UIButton中既添加文字,又添加图片的时候,图片是显示在文字的左边。

当我们实际需要图片显示在文字的右边的时候,需要重写UIButton的方法。

如下代码实现的功能就是:文字在左边,图片在右边。

- (id)initWithFrame:(CGRect)frame
{
self = [super
initWithFrame:frame];
if (self)
{
self.backgroundColor = [UIColor
purpleColor];
[self
setTitleColor:[UIColor
blackColor] forState:UIControlStateNormal];
self.titleLabel.textAlignment =
NSTextAlignmentCenter;
self.imageView.contentMode =
UIViewContentModeCenter;
}
return
self;
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat titleX =
0;
CGFloat titleY =
0;
CGFloat titleW =
self.width -
IWTitleImageWidth;
CGFloat titleH =
self.height;
return
CGRectMake(titleX, titleY, titleW, titleH);
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imageX =
self.width -
IWTitleImageWidth;
CGFloat imageY =
0;
CGFloat imageH =
self.height;
CGFloat imageW =
IWTitleImageWidth;
return
CGRectMake(imageX, imageY, imageW, imageH);
}

根据此原理,我们也可以调整图片在上,文字在下。

还有一种情况,就是让图片和文字有一定的距离,代码如下:

// 添加分享按钮
UIButton *shareButton = [[UIButton
alloc] init];
// 设置文字和颜色
[shareButton setTitle:@"分享给大家"
forState:UIControlStateNormal];
[shareButton setTitleColor:[UIColor
blackColor] forState:UIControlStateNormal];
// 设置图标
[shareButton setImage:[UIImage
imageWithName:@"new_feature_share_false"]
forState:UIControlStateNormal];
[shareButton setImage:[UIImage
imageWithName:@"new_feature_share_true"]
forState:UIControlStateSelected];

// 设置frame
shareButton.width =
200;
shareButton.height =
35;
shareButton.centerX =
self.view.width *
0.5;
shareButton.centerY =
self.view.height *
0.7;

shareButton.titleEdgeInsets =
UIEdgeInsetsMake(0,
20, 0,
0);//四个参数分别是距离top,left,bottom,right的距离。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: