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
相关产品推荐
相关产品推荐

