UIButton自定义图片文字位置

参考博客

iOS图片的填充方式UIImageView(contentMode)有什么不同

如何设置button的图片与文字位置

最近遇到了需要自定义button来设置它的图片文字相应区域位置的需求,话不多说,核心代码如下,关于代码中图片的填充方式可以看看上面的?参考博客,总结的很全面。

+ (instancetype)buttonWithFrame:(CGRect)frame title:(NSString *)title image:(UIImage *)image{
    ZHDTitleButton *button = [super buttonWithType:UIButtonTypeSystem];
    button.frame = frame;
    button.titleLabel.textAlignment = NSTextAlignmentCenter;
    [button setTintColor:[UIColor colorWithRed:0.48f green:0.50f blue:0.52f alpha:1.00f]];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    button.imageView.contentMode = UIViewContentModeCenter;
    [button setTitle:title forState:UIControlStateNormal];
    [button setImage:image forState:UIControlStateNormal];
    [button imageRectForContentRect:frame];
    [button titleRectForContentRect:frame];
    return button;
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect{
    CGFloat imageX = 0;
    CGFloat imageY = 12;
    CGFloat imageWidth = contentRect.size.width;
    CGFloat imageHeight = contentRect.size.height * (1 - 0.4);
    return CGRectMake(imageX, imageY, imageWidth, imageHeight);
}

- (CGRect)titleRectForContentRect:(CGRect)contentRect{
    CGFloat titleX = 0;
    CGFloat titleHeight = contentRect.size.height * 0.4;
    CGFloat titleY = contentRect.size.height - titleHeight + 10;
    CGFloat titleWidth = contentRect.size.width;
    return CGRectMake(titleX, titleY, titleWidth, titleHeight);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值