【问题标题】:How to scroll automatically when item appears in SwiftUI?当项目出现在 SwiftUI 中时如何自动滚动?
【发布时间】:2022-08-19 00:17:37
【问题描述】:

由于动画,我有一个垂直显示的名称列表,我希望在出现新名称时自动滚动,但我不知道如何继续......我看到了一些这样的问题,但所有它们是“跳转到数字”的解决方案,而不是逐步滚动……有什么建议吗?

更新代码:

struct ContentView: View {
    let correctNames = [\"Steve\", \"Bill\", \"John\", \"Elon\", \"Michael\", \"Justin\", \"Marcell\", \"David\", \"Gabriel\", \"Eric\", \"Jeffrey\", \"Taylor\", \"Jennifer\", \"Christian\"]
    @State private var animating = false
    
    var body: some View {
        VStack {
            ScrollView(showsIndicators: false) {
                ForEach(0..<correctNames.count, id: \\.self) { index in
                    Text(\"\\(correctNames[index])\")
                        .font(.system(size: 60))
                        .opacity(animating ? 1 : 0)
                        .animation(.easeIn(duration: 0.5).delay(Double(index) * 0.2), value: animating)
                }
            }
        }
        .onAppear {
            animating.toggle()
        }
    }
}
  • 使用滚动视图阅读器是 SwiftUI 中最重要的东西。使用 UIKit 你可以更细致,没有任何内置的东西

标签: ios swift swiftui scrollview


【解决方案1】:

我会以不同的方法(模型驱动和按项目)来完成所有这些工作,以更好地控制效果。

一种可能的方法是将项目逐个添加到事实源中,并根据此集合的增长添加效果。

这是一个演示。使用 Xcode 14 / iOS 16 测试

主要部分:

@State private var items = [Int]()   // storage

...

ScrollViewReader { sr in
    ScrollView(showsIndicators: false) {
      // ...
    }
}
.onAppear {
    items.append(1)   // initial item put
}

...

// iterating model ...
ForEach(items, id: \.self) { index in
    // content
    Text("\(index)").id(index).font(.system(size: 64))
    // ... it is appeared, so we can use transition
        .transition(index == items.last ? .opacity : .identity)
        .onAppear {
            // on last appeared scedule add next ...
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.82) {
                if index == items.last && index < 50 {
                    items.append(index + 1)
                }
                DispatchQueue.main.async {
                    // ... and animate scrolling to it after add
                    withAnimation {
                        sr.scrollTo(index + 1)
                    }
                }
            }
        }

Test code is here

【讨论】:

  • 我用一个不为空的字符串数组更新了我的代码,你能更新答案吗?
猜你喜欢
  • 2022-08-19
  • 2019-04-24
  • 1970-01-01
  • 2020-01-18
  • 2012-02-18
  • 1970-01-01
  • 2022-11-12
  • 2019-12-07
  • 1970-01-01
相关资源
最近更新 更多