动画在触摸时不起作用“开始”按钮突出显示

Animation not working on touchesBegan button highlight

提问人:PrateekS 提问时间:9/1/2023 最后编辑:HangarRashPrateekS 更新时间:9/3/2023 访问量:19

问:

我正在尝试使用按钮顶部的自定义 UIImageView 层突出显示按钮,调用 touchesBegan,但它没有动画。

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

// 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)
    } 
}

任何帮助都是值得赞赏的,谢谢。

iOS Swift 动画 UIBubutton 触摸开始

评论


答:

0赞 PrateekS 9/3/2023 #1

所以我弄清楚了我做错了什么: 我试图切换图像的颜色,但图像本身会立即附加,所以我真正应该做的是为附加图像的 alpha 设置动画,如下所示:

let color = UIColor.black.withAlphaComponent(0.5)
self.highlightBtn?.image = color.image()
self.highlightBtn?.alpha = isHighlighted ? 1 : 0
self.highlightBtn?.layer.compositingFilter = "softLightBlendMode"