Swift UIKit中UIButton setBackgroundImage不生效问题求助
以下是几个排查方向和修复方案:
先确认图片资源没问题
调用方法时传入的UIImage可能为nil,检查图片名称是否拼写正确、是否已添加到项目Assets目录或复制到项目中。可以先直接用setBackgroundImage(_:for:)测试静态设置是否能显示图片,排除资源本身的问题。匹配按钮的状态设置
你的代码只设置了.normal状态的背景图,如果按钮当前处于.selected、.highlighted等其他状态,新背景图不会显示。可以修改方法同时覆盖需要的状态,或者确保调用方法时按钮处于.normal状态:extension UIButton { func setBackgroundImageWithFade(_ image: UIImage?, duration: TimeInterval = 1.25, completion : ((Bool) -> Void)? = nil) { UIView.transition(with: self, duration: duration, options: .transitionCrossDissolve, animations: { // 同时设置多个需要的状态 self.setBackgroundImage(image, for: .normal) self.setBackgroundImage(image, for: .selected) self.setBackgroundImage(image, for: .highlighted) }, completion: completion) } }直接对按钮内部背景ImageView做动画
UIButton的背景图由内部私有UIImageView管理,直接对按钮本身做过渡动画可能不生效。可以尝试获取这个ImageView单独做动画:extension UIButton { func setBackgroundImageWithFade(_ image: UIImage?, duration: TimeInterval = 1.25, completion : ((Bool) -> Void)? = nil) { guard let bgImageView = self.subviews.first(where: { String(describing: type(of: $0)) == "_UIButtonBackgroundImageView" }) as? UIImageView else { self.setBackgroundImage(image, for: .normal) completion?(true) return } UIView.transition(with: bgImageView, duration: duration, options: .transitionCrossDissolve, animations: { bgImageView.image = image }, completion: completion) // 同步更新按钮状态背景图,避免状态切换时还原 self.setBackgroundImage(image, for: .normal) } }再次核对Storyboard按钮配置
确保按钮的Type确实是Custom,同时清空Storyboard中按钮的所有背景图设置,避免界面配置覆盖代码逻辑。
内容的提问来源于stack exchange,提问作者Aviram Netanel
相关产品推荐
相关产品推荐

