【问题标题】:Animating date changes in SwiftUISwiftUI 中的动画日期变化
【发布时间】:2020-10-29 12:42:43
【问题描述】:

我正在努力创建一个更改日期值的动画。下面是一个简化的例子。当日期从其原始值更新为新值时,它旨在通过更改值来更新文本视图。非常感谢您的帮助!

struct DateAnimationView: View {

    @State var date = Date()

    typealias AnimatableData = Date

    var animatableData: Date{
        get{date}
        set{date = newValue}
    }

    var body: some View {
        VStack{
            Text(date, style: .time)
                .padding()
            
            Button(action:{
                withAnimation(.linear(duration: 3.0)){
                    date.addTimeInterval(60 * 60 * 3)
                }
            }){
                Text("Add 3 hours")
            }
                .padding()
            Spacer()
        }
    }
}

又一次失败的尝试:

struct InnerView: View {
    var date: Date
    var interval: TimeInterval
        
    typealias AnimatableData = TimeInterval
    
    var animatableData: TimeInterval{
        get{interval}
        set{interval = newValue}
    }
    
    var body: some View{
        Text(date.addingTimeInterval(interval), style: .time)
    }
}

struct DateAnimationView: View{
    @State var isOn: Bool = false
    var body: some View{
        VStack{
            InnerView(date: Date(), interval: isOn ? 60*60*3 : 0)
            Button(action:{
                isOn.toggle()
            }){
                Text("Go")
            }
        }
    }
}

【问题讨论】:

    标签: animation swiftui


    【解决方案1】:

    基本思想是您需要为要制作动画的组件指定一个 id。 SwiftUI 在重绘时使用这个 id 来了解它是同一个组件还是新组件。如果它是一个新组件,它将删除旧组件并添加一个带有动画的新组件。下面的代码实现了动画。

    struct DateAnimationView: View {
        @State var date = Date()
    
        typealias AnimatableData = Date
    
        var animatableData: Date{
            get{date}
            set{date = newValue}
        }
    
        var body: some View {
            VStack{
                Text(date, style: .time)
                    .padding()
                    .id(String(date.hashValue))
                
                Button(action:{
                    withAnimation(.linear(duration: 3.0)){
                        date.addTimeInterval(60 * 60 * 3)
                    }
                }){
                    Text("Add 3 hours")
                }
                    .padding()
                Spacer()
            }
        }
    }
    

    解决方案posted here解决了类似的问题。

    【讨论】:

    • 感谢您的快速响应。不幸的是,添加 id 似乎没有按预期工作。现在这两个日期值被简单地叠加了。需要明确的是,我希望在接近新时间时看到文本“计数”时间值。 (即:8:13 -> 8:42 -> 9:15 -> 10:22 -> 11:13)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多