swift - 属性更改时的动画 View SwiftUI

标签 swift swiftui

我有一个观点

struct CellView: View {
    @Binding var color: Int
    @State var padding : Length = 10
    let colors = [Color.yellow, Color.red, Color.blue, Color.green]

    var body: some View {
        colors[color]
            .cornerRadius(20)
            .padding(padding)
            .animation(.spring())
    }
}

我希望它在属性 color 更改时具有填充动画。我想将内边距从 10 设置为 0。

我尝试使用onAppear

    ...onAppear {
      self.padding = 0
    }

但它只在 View 出现时起作用一次(按预期),并且我想每次当属性 color 更改时都执行此操作。基本上,每次 color 属性更改时,我都希望将填充从 10 动画到 0。请问您是否有办法做到这一点?

最佳答案

正如您在其他答案中注意到的那样,您无法从 body 内更新状态。您也不能像使用 @State 那样在 @Binding 上使用 didSet(至少从 Beta 4 开始)。

我能想到的最佳解决方案是使用 BindableObjectsink/onReceive 来更新每个 上的 padding >颜色改变。我还需要添加延迟才能完成填充动画。

class IndexBinding: BindableObject {
    let willChange = PassthroughSubject<Void, Never>()
    var index: Int = 0 {
        didSet {
            self.willChange.send()
        }
    }
}

struct ParentView: View {
    @State var index = IndexBinding()
    var body: some View {
        CellView(index: self.index)
            .gesture(TapGesture().onEnded { _ in
                self.index.index += 1
            })
    }
}

struct CellView: View {

    @ObjectBinding var index: IndexBinding
    @State private var padding: CGFloat = 0.0

    var body: some View {
            Color.red
                .cornerRadius(20.0)
                .padding(self.padding + 20.0)
                .animation(.spring())
                .onReceive(self.index.willChange) {
                    self.padding = 10.0
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
                        self.padding = 0.0
                    }
                }
    }
}


此示例不会在 Beta 4 上的 Xcode Canvas 中显示动画。请在模拟器或设备上运行它。

关于swift - 属性更改时的动画 View SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57260740/

相关文章:

ios - 当我从自定义构建配置存档时缺少文件

swift - 如何在 swift4 中获取 Sqlite3 中的表总数?

ios - 未找到目标,请重新连接设备,Xcode :Device Support File

SwiftUI 拖放文件

ios - 当 SwiftUI Picker 选择更改 EnvironmentObject 时,有没有办法调用函数?

ios - VC之间传递数据失败

ios - 测试 Xcode 项目时无法访问 AppDelegate

swift - SwiftUI 中 NavigationBarTitle 中的额外间距

swift - 是否可以从 SwiftUI 使用 ASWebAuthenticationSession ?

ios - UITableView 以编程方式滚动到不存在的单元格