交换Button中图片与文字左右位置

交换Button中图片与文字左右位置

默认情况下,button的image和label是紧贴着居中的,那如果想要image在右边,label在左边应该怎么办呢?

答案就是:

self.oneButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
self.oneButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWith, 0, imageWith);

来解释一下为什么:
其实就是这一句:This property is used only for positioning the image during layout
其实titleEdgeInsets属性和 imageEdgeInsets属性只是在画这个button出来的时候用来调整image和label位置的属性,并不影响button本身的大小。
它们只是image和button相较于原来位置的偏移量,那什么是原来的位置呢?就是没有设置edgeInset时候的位置了。

如果要image在右边,label在左边,那image的左边相对于button的左边右移了labelWidth的距离,image的右边相对于label的左边右移了labelWidth的距离

所以,self.oneButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);为什么是负值呢?因为这是contentInset,是偏移量,不是距离

同样的,label的右边相对于button的右边左移了imageWith的距离,label的左边相对于image的右边左移了imageWith的距离

所以self.oneButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWith, 0, imageWith);

// 继承button,重写该方法
- (void)layoutSubviews
{
    [super layoutSubviews];

    if (self.currentImage == nil) return;

    CGFloat imageW = self.imageView.width;
    CGFloat labelW = self.titleLabel.width;

    self.imageEdgeInsets = UIEdgeInsetsMake(0, labelW, 0, -labelW);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, -imageW, 0, imageW);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值