动画不适用于触摸开始按钮突出显示

问题描述 投票:0回答:1

我试图使用按钮顶部的自定义 UIImageView 层来突出显示按钮,调用 TouchBegan,但它没有动画。

它工作得很好,除了我似乎无法让它对突出显示进行动画处理,我为 collectionView 编写了类似的代码,使用 didHighlightItemAt 可以正确地进行动画处理,在按钮的情况下我做错了什么或者这里的解决方法是什么?

// For btn highlight
    func highlight(isHighlighted: Bool) {
        UIView.animate(withDuration: 0.08, delay: 0, options: [.allowUserInteraction, .overrideInheritedOptions, .curveEaseOut], animations: {
            let color = isHighlighted ? UIColor.black.withAlphaComponent(0.5) : .clear
            self.highlightBtn?.image = color.image()
            self.highlightBtn?.layer.compositingFilter = "softLightBlendMode"
        })
    }
    
    @IBAction func touchBeganButton(_ sender: UIButton) {
        highlight(isHighlighted: true)
        btnFollow.layer.borderWidth = 1.8
    }
    
    @IBAction func touchEndedButton(_ sender: UIButton) {
        highlight(isHighlighted: false)
        btnFollow.layer.borderWidth = 1.5
    }
    
    @IBAction func touchCancelButton(_ sender: UIButton) {
        highlight(isHighlighted: false)
        btnFollow.layer.borderWidth = 1.5
    }

我尝试使用类(下面的代码)突出显示,但按钮可以具有不同的颜色,具体取决于 API 调用,因此它必须是相同颜色的变暗效果,这就是我使用 ImageView 的原因。

@IBDesignable
class HighlightButton: UIButton {
    
    @IBInspectable var normalBackgroundColor: UIColor? {
        didSet {
            backgroundColor = normalBackgroundColor
        }
    }
    
    @IBInspectable var highlightedBackgroundColor: UIColor?
    
    override var isHighlighted: Bool {
        didSet {
            if oldValue == false && isHighlighted {
                highlight()
            } else if oldValue == true && !isHighlighted {
                unHighlight()
            }
        }
    }
    
    var highlightDuration: TimeInterval = 0.08

    private func animateBackground(to color: UIColor?, duration: TimeInterval) {
        guard let color = color else { return }
        UIView.animate(withDuration: highlightDuration) {
            self.backgroundColor = color
        }
    }

    func highlight() {
        animateBackground(to: highlightedBackgroundColor, duration: highlightDuration)
    }

    func unHighlight() {
        animateBackground(to: normalBackgroundColor, duration: highlightDuration)
    } 
}

感谢任何帮助,谢谢。

swift xcode animation touchesbegan
1个回答
0
投票

所以我明白了我做错了什么: 我试图切换图像的颜色,但图像本身会立即附加,所以我真正应该做的是对附加图像的 alpha 进行动画处理,如下所示:

let color = UIColor.black.withAlphaComponent(0.5)
self.highlightBtn?.image = color.image()
self.highlightBtn?.alpha = isHighlighted ? 1 : 0
self.highlightBtn?.layer.compositingFilter = "softLightBlendMode"
© www.soinside.com 2019 - 2024. All rights reserved.