Question

我正在try 将UIView的 colored颜色 从浅灰色设置为深灰色,将UIButton标题的 colored颜色 从蓝色设置为橙色.

当点击UIButton时,动画将在3秒内发生.

UIView会在3秒内改变 colored颜色 ,但UIButton不会,并且会立即改变 colored颜色 .

  • 为什么UIButton标题的彩色动画没有达到预期的效果?

  • 如何特别使用UIView.Animate使动画工作?

谢谢.


Code

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

推荐答案

调用UIButton的setTitleColor(_:for:)方法不会对 colored颜色 更改进行动画处理,因为它是不可动画的.类似于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)

Ios相关问答推荐

在Android和iOS上从后台恢复应用程序后,inappwebview上出现白屏?

使用SWIFT传输表示时的条件文件表示格式

如何使用Xcode15.1在iMessage扩展模块中显示贴纸

Xcode -Google Mobile Ads SDK在没有AppMeasurement的情况下初始化

如果没有等待,SWIFT Async让任务抛出取消异常

无法向委托发送数据

在 SwiftUI 中以编程方式插入内嵌图像

_SKStoreProductParameterAdNetworkSourceIdentifier未定义符号

无法在 CollectionView 中禁用部分弹跳 - 组合布局

SwiftUI:如何用拇指移动滑块值

Xcode 14 需要为 Pod Bundles Select 开发团队

如何识别 SwiftUI 中点击的按钮 ID 以使该按钮动画化?

无法同时满足约束 - 没有适当的约束

如何在 Swift 3 中根据 UIImage 的大小/比率调整 UIImageView 的大小?

关闭所有打开的视图控制器的单个函数

动画 UILabel 字体大小更改

标题为 UIImage 的导航栏

在 React Native 中保存敏感数据

有没有办法在应用store 之外分发 ios 应用程序?

检测应用程序何时进入我的视图背景的最佳方法是什么?