iOS控件开发-UIButton的UIEdgeInsets

903 阅读1分钟

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;
  • specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
  • 解释:对每条边向内方向的偏移量,可以为正值(向内偏移)也可以为负值(向外偏移)。
图解

WX20210827-153632.png

基本使用:

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的内偏移量与其他控件有些区别。
因为UIButton内部默认有两个子控件:UILabel和UIImageView
所以UIButton在内偏移量的计算上会有差异

image.png

这种场景下UIEdgeInsets是这样一个相对位置:
  • title的 上边线、右边线、下边线 内偏移 是相对于contentView的
  • image的 上边线、左边线、下边线 内偏移 是相对于contentView的
  • title的 左边线 内偏移 相对于image
  • image的 右边线 内偏移 相对于title

这里列举图片与文字的组合的四种位置方式。

  • image左 title右
  • image右 title左
  • image上 title下
  • image下 title上 这里偏移量设定为10.
场景一:左图右字
button.titleEdgeInsets = UIEdgeInsetsMake(0, 10.0, 0, 0);

image.png

场景二:右图左字
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);

image.png

场景三:上图下字
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);

image.png

场景四:下图上字