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

UIButton动画标题位置异常左跳,需保持标题始终居中

解决UIButton动画时标题左跳的问题

嘿,这个坑我之前踩过!你遇到的问题是因为直接修改bounds.size.width时,UIButton的内部布局系统在动画过程中没有正确维持标题的居中对齐,导致弹簧动画的过程中标题突然左跳。下面给你几个靠谱的解决方案:

方案一:用Transform缩放代替修改Bounds

这种方法最省心,因为transform是对整个按钮视图做缩放变换,内部的titleLabel会自动跟着保持居中位置,不会出现布局跳变:

// 先计算缩放比例,比如原宽度是200,要减80就是120,缩放比例就是120/200=0.6
let targetWidth = self.loginButton.bounds.width - 80.0
let scaleX = targetWidth / self.loginButton.bounds.width

UIView.animate(withDuration: 1.5, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.0) {
    self.loginButton.transform = CGAffineTransform(scaleX: scaleX, y: 1.0)
} completion: { _ in
    // 如果需要最终将bounds固定到目标宽度,可以在动画结束后还原transform并设置bounds
    self.loginButton.bounds.size.width = targetWidth
    self.loginButton.transform = .identity
}

方案二:强制标题居中对齐

通过设置titleLabel的对齐方式和按钮的内边距,让按钮在布局时始终强制标题居中,避免bounds变化时的布局偏差:

// 提前设置按钮的标题对齐和内边距,确保布局稳定
self.loginButton.titleLabel?.textAlignment = .center
self.loginButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
self.loginButton.titleEdgeInsets = .zero

// 执行动画
UIView.animate(withDuration: 1.5, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.0) {
    self.loginButton.bounds.size.width -= 80.0
} completion: { _ in
    // 动画结束后的后续操作
}

方案三:用Auto Layout约束修改宽度

如果你的按钮是用Auto Layout布局的,直接修改宽度约束的constant是最符合iOS布局系统的方式,系统会自动平滑处理标题的位置:

// 假设你已经把按钮的宽度约束关联到了loginButtonWidthConstraint这个IBOutlet
UIView.animate(withDuration: 1.5, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.0) {
    self.loginButtonWidthConstraint.constant -= 80.0
    self.view.layoutIfNeeded() // 必须调用这个来触发布局更新动画
} completion: { _ in
    // 后续操作
}

额外小提醒

如果你用的是自定义UIButton,记得检查有没有重写layoutSubviews方法,会不会在里面手动修改了titleLabel的frame,这可能会和动画的布局逻辑冲突哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:23:12