【问题标题】:SwiftUI: animating scroll on ScrollView programmatically?SwiftUI:以编程方式在 ScrollView 上设置滚动动画?
【发布时间】:2021-07-15 18:58:17
【问题描述】:

我需要以编程方式为滚动视图的滚动设置动画。滚动视图包含 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...

如何为滚动设置动画?

【问题讨论】:

    标签: swiftui scrollviewreader


    【解决方案1】:

    如果您从其他地方启动交互式滚动(例如 Button 操作)而不是从 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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多