Swift中UIButton高亮状态下动画图片褪色/透明的问题求助
我给UIBarButtonItem的自定义视图(PlusButton)实现了旋转45°的动画,将“+”图标转为“x”样式。但按钮处于高亮状态时,“+”图片会出现褪色/透明现象;取消高亮后,动画从“x”转回“+”则无异常。需要实现高亮状态下图片与动画不褪色的效果。
现有代码
自定义PlusButton类
class PlusButton: UIButton { override var isHighlighted: Bool { didSet { if isHighlighted == true { animateTurn45() } else { animateTurnNeg45() } } } func animateTurn45() { let rotationTransform = CGAffineTransform(rotationAngle: CGFloat.pi / 4) UIView.animate(withDuration: 0.5, animations: { self.transform = rotationTransform }) { (_) in // Animation completion handler } } func animateTurnNeg45() { UIView.animate(withDuration: 0.5, animations: { self.transform = .identity }) { (_) in // Animation completion handler } } }
按钮作为UIBarButtonItem customView的代码
let plusButton = PlusButton() plusButton.setBackgroundImage(UIImage(systemName: "plus"), for: .normal) plusButton.menu = UIMenu(title: "", children: menuItems) popUpPlusButton.customView = plusButton
状态截图
- 初始状态:

- 高亮状态:

- 取消高亮后状态:

解决方法
问题源于UIButton默认的高亮状态行为——系统会自动给背景图片添加褪色效果,以下是三种可行解决方案:
方案1:统一高亮与正常状态的背景图片
直接给.highlighted状态设置和.normal相同的图片,覆盖系统默认的褪色处理:
let plusImage = UIImage(systemName: "plus") plusButton.setBackgroundImage(plusImage, for: .normal) plusButton.setBackgroundImage(plusImage, for: .highlighted) // 关键代码
方案2:禁用图片高亮自动调整
在PlusButton类中重写adjustsImageWhenHighlighted属性,彻底关闭系统对高亮状态图片的自动调整:
override var adjustsImageWhenHighlighted: Bool { get { return false } set { } }
方案3:使用image替代backgroundImage(SF Symbols场景推荐)
将SF Symbols设置为按钮的image而非backgroundImage,系统的高亮褪色影响会更小,还能通过tintColor统一控制图标颜色:
plusButton.setImage(UIImage(systemName: "plus"), for: .normal) plusButton.setImage(UIImage(systemName: "plus"), for: .highlighted) // 可选,或配合方案2禁用自动调整
该方案下旋转动画依然正常生效,因为动画是对整个按钮的transform进行操作,不影响图标的显示逻辑。
内容的提问来源于stack exchange,提问作者Nikola Blazevic
相关产品推荐
相关产品推荐

