使用UIEdgeInsets布局UIButton

您可以使用插图来布局系统或自定义按钮的内容。 通过插入,您可以为按钮的标题( titleEdgeInsets ),图像( imageEdgeInsets )以及标题和图像( contentEdgeInsets )一起添加或删除空间。

要查看这三个属性的工作原理,请通过xib文件或创建一个按钮( UIButton 在代码中。 在超级视图约束中,仅在垂直和水平方向上给它一个中心,在第一个示例中,不给它一个宽度上的约束。 为contentView提供蓝色背景色,为imageView提供红色背景色,为titleLabel提供黄色背景色。 最重要的是,您还可以为按钮的边框赋予绿色。

  button.backgroundColor = .blue 
button.imageView?.backgroundColor = .red
button.titleLabel?.backgroundColor = .yellow
button.layer.borderColor = UIColor.green.cgColor
button.layer.borderWidth = 2

contentEdgeInsets的行为符合您的预期。 您可以使用正值在imageViewtitleLabel周围添加空间。

 让间距:CGFloat = 8.0 
button.contentEdgeInsets = UIEdgeInsets(顶部:0,左侧: 间距 ,底部:0,右侧: 间距

当涉及titleEdgeInsetsimageEdgeInsets时,规则是向左右插图添加相等和相反的偏移量。 因此,例如,如果在左侧标题插图上添加8点,则需要在右侧插图上加上-8点。 这样,您仅使用插图来偏移标题或图像,而不以任何方式调整它们的大小。 如果不执行此操作,则计算的布局矩形可能会变得太小,标题可能会被截断,并且间距将显示一些奇怪的行为。

  button.titleEdgeInsets = UIEdgeInsets(top:0,left:interval,bottom:0,right: 0

要翻转带有图像的标题,我们可以使用imageEdgeInsetstitleEdgeInsetsimageView移动到titleLabel后面 首先,我们将imageView的大小与按钮宽度向右移动,然后减去该图像的宽度,以使imageView保留在内容视图中。 它看起来像这样:

我们为右插图设置左插图的相反值:

 让buttonWidth = button.frame.width 
让imageWidth = button.imageView!.frame.width
  button.imageEdgeInsets = UIEdgeInsets(top:0,left: buttonWidth-imageWidth ,bottom:0,right :-(buttonWidth-imageWidth)

然后,我们可以将titleLabel以与imageView的宽度相同的数量向左移动:

  button.titleEdgeInsets = UIEdgeInsets(top:0,left: -imageWidth ,bottom:0,right: imageWidth

如果要在imageViewtitleLabel之间一些间距,则需要像这样将一半的间距添加到titleLabel并将一半的间距添加到imageView

 让buttonWidth = button.frame.width 
让imageWidth = button.imageView!.frame.width
让间距:CGFloat = 8.0 / 2
  button.imageEdgeInsets = UIEdgeInsets(顶部:0,左侧:buttonWidth-imageWidth +间距 ,底部:0,右侧:-(buttonWidth-imageWidth) -间距
  button.titleEdgeInsets = UIEdgeInsets(顶部:0,左侧:-imageWidth- 间距 ,底部:0,右侧:imageWidth +间距

但是titleLabel和图像eView现在超出了内容视图。 我们可以用contentEdgeInsets来弥补:

  button.contentEdgeInsets = UIEdgeInsets(顶部:0,左侧:间距,底部:0,右侧:间距) 

但是,如果我们要使imageView在后边缘具有一定的边距,并且titleLabel居中,该怎么办?

我们可以通过给按钮更大的间距(例如128点)来增大按钮的尺寸。 然后,我们需要将imageView的按钮宽度加上右边的间距减去我们希望图像从右边缘开始的边距(本例中为16点)。 然后,我们必须在right edgeInset中补偿相同但相反的间距,以使imageView保持相同大小。

添加图像时,标题会以图像宽度的数量推到右侧。 在上面的示例中, imageViewtitleLabel一起居中,但是现在我们只需要将titleLabel居中 。 为此,我们将左右titleEdgeInset设置为imageView宽度的一半。 我们在两边都这样做,以保持titleLabel的大小相同,否则,您将获得截断的标题。

  button.imageEdgeInsets = UIEdgeInsets(顶部:0,左侧:buttonWidth +间距— imageWidth — 16,底部:0,右侧:-spacing) 
  button.titleEdgeInsets = UIEdgeInsets(顶部:0,左侧:-imageWidth / 2,底部:0,右侧:imageWidth / 2) 
  button.contentEdgeInsets = UIEdgeInsets(顶部:0,左侧:间距,底部:0,右侧:间距) 

当您为按钮设置宽度限制时,可以将边距设置为0或将所有边距都保留。 宽度约束将已经扩大内容视图。