码农的世界IOSios

iOS UIButton之UIEdgeInsets详解

2018-08-01  本文已影响190人  齐舞647

我们先看一下苹果官方对UIEdgeInsets说明:

typedef struct UIEdgeInsets {
    CGFloat top, left, bottom, right;  
// specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
} UIEdgeInsets;

基本使用:

xxx.edgeInsets = UIEdgeInsetsMake(.0, .0, .0, .0);

//例如我们设置UICollectionView的edgeInset会使collectionView产生内偏移
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.sectionInset = UIEdgeInsetsMake(20.0, .0, .0, .0);

引入正题:
然而,UIButton的内偏移量与其他控件有些区别,
因为UIButton内部默认有两个子控件:UILabel和UIImageView
所以UIButton在内偏移量的计算上会有差异。
为什么?先卖个关子,下文解释。

UIButton默认子控件位置

UIButtonEdgeInsets:

需求:通过修改edgeInsets,改变Button内部的ImageView和titleLabel的相对位置。

小编做了一个demo,效果如下图:

Demo效果图

思路:通过修改button的两个属性:titleEdageInsets和imageEdgeInsets,从而达到最终的具体需求。这里列出了三个比较常见的需求:

场景一:左图右字

button.titleEdgeInsets = UIEdgeInsetsMake(0, 10.0, 0, 0);

语法解释:设置了title的左边线的内偏移量为10.0,

但经测试,
注意:实际上title和Image直接只有5.0的距离
注意:实际上title和Image直接只有5.0的距离
注意:实际上title和Image直接只有5.0的距离

图解如下:

在这种场景下:

场景二:左字右图

button.titleEdgeInsets = UIEdgeInsetsMake(.0, - button.imageView.bounds.size.width - 10.0, .0, button.imageView.bounds.size.width);
button.imageEdgeInsets = UIEdgeInsetsMake(.0, button.titleLabel.bounds.size.width, .0, - button.titleLabel.bounds.size.width);

语法解释:

是不是有点绕人?哈哈,不要慌,请看图解

场景三:上图下字

button.titleEdgeInsets = UIEdgeInsetsMake(button.imageView.frame.size.height + 10.0, - button.imageView.bounds.size.width, .0, .0);
button.imageEdgeInsets = UIEdgeInsetsMake(.0, button.titleLabel.bounds.size.width / 2, button.titleLabel.frame.size.height + 10.0, - button.titleLabel.bounds.size.width / 2);

语法解释:

请看图解:

本文Demo链接:https://github.com/QiShare/QiButton_UIEdgeInsets

上一篇 下一篇

猜你喜欢

热点阅读