代码之家  ›  专栏  ›  技术社区  ›  Brewski

使用animateKeyframes的UI动画对按钮标题颜色没有任何影响

  •  0
  • Brewski  · 技术社区  · 4 年前

    我正试图为我的颜色设置动画 UI按钮 标题颜色 使用 animate关键帧 但它除了加载动画中的最后一个状态(在本例中为purpleText)外,什么也不做。我使用相同的代码来设置按钮颜色和UIView背景颜色的动画,没有任何问题。

    我也检查了一下,把按钮改成了 自定义按钮 在里面 界面生成器 但这也无济于事。

            UIView.animateKeyframes(withDuration: 12, delay: 12, options: [.allowUserInteraction, .repeat, .autoreverse], animations: {
                UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.25, animations: {
                    self.infoButton.setTitleColor(blueText, for: UIControlState.normal)
                })
                UIView.addKeyframe(withRelativeStartTime: 0.2, relativeDuration: 0.25, animations: {
                    self.infoButton.setTitleColor(greenText, for: UIControlState.normal)
                })
                UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.25, animations: {
                    self.infoButton.setTitleColor(yellowText, for: UIControlState.normal)
                })
                UIView.addKeyframe(withRelativeStartTime: 0.6, relativeDuration: 0.25, animations: {
                    self.infoButton.setTitleColor(redText, for: UIControlState.normal)
                })
                UIView.addKeyframe(withRelativeStartTime: 0.8, relativeDuration: 0.25, animations: {
                    self.infoButton.setTitleColor(purpleText, for: UIControlState.normal)
                })
            }, completion: nil)
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   aheze But I'm Not A Wrapper Class    4 年前

    打电话 setTitleColor() 动画块内部不起作用,因为 UIView.animate 仅适用于可设置动画的属性,如 infoButton.backgroundColor .

    不幸的是,按钮属性如 tintColor aren't animatable 。你也不应该直接访问按钮的 titleLabel ,即 nil 用于系统按钮。

    相反,您可以使用 UIView.transition 具有 setTitleColor() 。然后你可以把它放在 Timer …我通常不喜欢在动画中使用计时器,但我想不出其他方法。

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        let colors: [UIColor] = [.blue, .green, .yellow, .red, .purple]
        var currentIndex = 0
        
        _ = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { timer in
            if colors.indices.contains(currentIndex) {
                UIView.transition(with: self.infoButton, duration: 0.5, options: [.transitionCrossDissolve, .allowUserInteraction]) {
                    self.infoButton.setTitleColor(colors[currentIndex], for: .normal)
                }
                currentIndex += 1
            } else {
                currentIndex = 0
            }
        }
    }
    

    结果:

    Button title color animates and cycles