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

默认情况下,在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的距离。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值