1

我需要以编程方式为滚动视图的滚动设置动画。滚动视图包含 HStack 或 VStack。我测试的代码是这样的:

        ScrollViewReader { proxy in
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: spacing) {
                    
                    ForEach(cids, id: \.self) { cid in

                        ....
                                
                    }
                    
                }
                .onAppear {
                    withAnimation(Animation.easeInOut(duration: 4).delay(3)) {
                        proxy.scrollTo(testCid)
                    }
                    
                }
            }
            .frame(maxWidth: w, maxHeight: w / 2)
        }

滚动视图确实落在带有 的项目上testCid,但是它没有动画。一旦视图出现在屏幕上,滚动视图就已经打开了testCid......

如何为滚动设置动画?

4

1 回答 1

1

如果您从其他地方(feButton动作)而不是从onAppear修饰符启动交互式滚动,则它会起作用。我猜这是故意的行为,以防止用户在视图出现时看到滚动(或 SwiftUI 中的错误......)。一个丑陋的解决方法是用一个推迟动画DispatchQueue.main.async

import SwiftUI

struct ContentView: View {
    let words = ["planet", "kidnap", "harbor", "legislation", "soap", "management", "prejudice", "an", "trunk", "divide", "critic", "area", "affair"]

    @State var selectedWord: String?

    var body: some View {
        ScrollViewReader { proxy in
            VStack(alignment: .leading) {
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(spacing: 10) {
                        ForEach(words, id: \.self) { word in
                            Text(word)
                                .background(self.selectedWord == word ? Color.yellow : nil)
                                .id(word)
                        }
                    }
                }

                Button("Scroll to random word") {
                    withAnimation(Animation.easeInOut(duration: 1)) {
                        let word = words.randomElement()
                        self.selectedWord = word
                        proxy.scrollTo(word)
                    }
                }
            }
            .onAppear {
                DispatchQueue.main.async {   // <--- workaround
                    withAnimation(Animation.easeInOut(duration: 1).delay(1)) {
                        let word = self.words.last
                        self.selectedWord = word
                        proxy.scrollTo(word)
                    }
                }
            }
        }
        .padding(10)
    }
}
于 2021-07-16T15:31:46.053 回答