SwiftUI 如何临时为 View 颜色的foregroundColor 设置动画?

标签 swift animation swiftui

当按下 View 时,我通过模型知道 button.isSelected .如何为 View 的前景色设置动画,类似于 IOS 计算器按钮按下动画?
就像是:
白色 -> 灰色 -> 白色

struct ButtonView: View {
    let button: ViewModel.Button

    
    var body: some View {
        let shape = Rectangle()
        ZStack {
            shape.fill().foregroundColor(button.isSelected ? Color.gray : Color.white)
                .animation(Animation.linear(duration: 0.01))
            .border(Color.black, width: 0.33)
            Text(button.content)
            .font(Font.system(size:32))
            
        }
    }
}

最佳答案

我认为有很多方法可以做到这一点。
其中,我会用DispatchQueue.main.asyncAfter()写一个例子

struct ContentView: View {
    @State private var isSelected: Bool = false
    
    var body: some View {
        VStack {
            Button {
                isSelected = true
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2 ) {
                    // To change the time, change 0.2 seconds above
                    isSelected = false
                }
            } label: {
                Text("Button")
                    .foregroundColor(isSelected ? Color.red : Color.blue)
            }
        }
    }
}

关于SwiftUI 如何临时为 View 颜色的foregroundColor 设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68448273/

相关文章:

Swift:UISearchController 不在窗口层次结构中

ios - firebase 数据库结构的好方法,以便按日期排序?

css - 形状 "8"仅使用 SVG <animate> 的循环动画

swift - 在 View 中不可变的一些 View 主体变量/不透明返回

ios - Swift 3 中的递归字典

ios - 如何使用 UIPageViewController 在第一个和最后一个索引处停止 UIScrollView 的弹跳?

javascript - 带有焦点的输入示例打破表单的向下滑动动画

iOS Swift - 改变背景颜色

swift - Xcode 不会让我在可选的上使用 `@ObservedObject`

swift - 如何使 SwiftUI 选择器自动换行