ios 奇怪的UIView.animate行为改变UIButton标题颜色

juzqafwq  于 2023-06-25  发布在  iOS
关注(0)|答案(2)|浏览(127)

问题

我试图动画的UIView颜色从浅灰色到深灰色和UIButton标题颜色从蓝色到橙子。
当点击UIButton时,动画将在3秒内发生。
UIView会在3秒内改变颜色,但UIButton不会,并且会立即改变颜色。

  • 为什么UIButton标题颜色动画不按预期工作?
  • 我如何让动画特别使用UIView.animate工作?

谢谢你。

编码

import UIKit

class ViewController: UIViewController {
    
    let button = UIButton(type: .system)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Set view colour
        self.view.backgroundColor = .lightGray

        // Set initial title color
        button.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
        button.setTitle("Button", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 50)
        view.addSubview(button)
        
        // Add tap gesture recognizer to trigger animation
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(buttonTapped))
        button.addGestureRecognizer(tapGesture)

    }
    
    @objc func buttonTapped() {
        
        // Animate the change of view and title color
        UIView.animate(withDuration: 3, delay: 0, options: [.beginFromCurrentState, .curveEaseInOut], animations: {
            self.view.backgroundColor = .darkGray
            self.button.setTitleColor(.orange, for: .normal)
        })
        
    }
    
}
gajydyqb

gajydyqb1#

调用UIButton的setTitleColor(_:for:)方法不会对颜色更改进行动画处理,因为它是不可动画处理的。类似于https://stackoverflow.com/a/67323728/8263578
如果没有UIView.animate方法也没问题,可以使用以下代码块:

// Animate the change of button title color
UIView.transition(with: button, duration: 3, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: {
    self.button.setTitleColor(.orange, for: .normal)
}, completion: nil)
yizd12fk

yizd12fk2#

请在buttonTapped()函数上这样尝试:

UIView.animate(withDuration: 3, delay: 0, options: [.beginFromCurrentState, .curveEaseInOut], animations: {
        self.view.backgroundColor = .darkGray
    })
    
UIView.animate(withDuration: 3, delay: 0, options: [.beginFromCurrentState, .curveEaseInOut], animations: {
    self.button.setTitleColor(.orange, for: .normal)
})

相关问题