You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决代码设置UIButton图片和标题后标题未在图片上居中的问题

UIButton代码设置图片和标题后布局偏移解决方案

问题原因

默认UIButton的自带布局规则是「图片居左、标题居右,二者横向排列留有默认间距」,你在Storyboard中设置的静态布局配置没有适配代码修改后的图片、标题尺寸,因此会出现标题偏移到图片左侧的问题。

适配方案

方案1:手动调整内边距(兼容iOS 14及更低版本)

通过修改imageEdgeInsets和titleEdgeInsets属性调整图片和标题的位置,示例代码如下:

// 先完成图片、标题的赋值
startButton.setImage(UIImage(named: "StartButton"), for: .normal)
startButton.setAttributedTitle(NSAttributedString(string: "START"), for: .normal)
// 强制刷新布局拿到当前图片、标题的实际尺寸
startButton.layoutIfNeeded()

guard let imageSize = startButton.imageView?.frame.size,
      let titleSize = startButton.titleLabel?.frame.size else { return }

// 调整图片内边距,抵消标题宽度的占位
startButton.imageEdgeInsets = UIEdgeInsets(
    top: 0,
    left: 0,
    bottom: 0,
    right: -titleSize.width
)
// 调整标题内边距,抵消图片宽度的占位,让标题覆盖到图片上方
startButton.titleEdgeInsets = UIEdgeInsets(
    top: 0,
    left: -imageSize.width,
    bottom: 0,
    right: 0
)
  • 如果需要调整标题的上下位置,修改titleEdgeInsets的top参数即可,正值向下偏移、负值向上偏移
  • 每次修改按钮的图片或标题内容后,都要重新执行上述边距计算逻辑,避免尺寸变化后布局错位

方案2:使用UIButton.Configuration(推荐,适配iOS 15及更高版本)

iOS 15推出的UIButton.Configuration可以直接配置按钮元素的布局规则,无需手动计算边距:

var config = UIButton.Configuration.plain()
config.image = UIImage(named: "StartButton")
config.attributedTitle = AttributedString("START")
// 设置标题居中对齐
config.titleAlignment = .center
// 取消图片和标题的默认间距
config.imagePadding = 0
// 如需调整整体内容的内边距可以修改config.contentInsets
config.contentInsets = .zero
// 赋值配置到按钮
startButton.configuration = config
  • 如需让标题覆盖在图片正中间,可将config.imagePlacement设置为.top,再把config.imagePadding调整为负的图片高度即可实现叠加效果

内容的提问来源于stack exchange,提问作者uyarc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:54:08