SwiftUI会自动滚动到ScrollView的底部(从下至上) [英] SwiftUI automatically scroll to bottom in ScrollView (Bottom first)

查看:644
本文介绍了SwiftUI会自动滚动到ScrollView的底部(从下至上)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是(在SwiftUI中)我有一个带有foreach的ScrollView.知道foreach何时加载所有我的条目,我希望最后一个条目集中.

My problem is that i have (in SwiftUI) a ScrollView with an foreach inside. Know when the foreach loads all of my entries i want that the last entry is focused.

我做了一些Google研究,但找不到任何答案.

I did some google research, but i didn't find any answer.

  ScrollView {
    VStack {
      ForEach (0..<self.entries.count) { index in
        Group {
          Text(self.entries[index].getName())
        }
      }
    }
  }

推荐答案

使用ScrollViewReader

的iOS14解决方案 iOS14中的

SwiftUI获得了一项新功能.为了能够在ScrollView中滚动到特定位置.有一个名为ScrollViewReader的新类型,其作用与Geometry Reader相同.

Solution for iOS14 with ScrollViewReader

in iOS14 SwiftUI gains a new ability. To be able to scroll in a ScrollView up to a particular location. There is a new type called ScrollViewReader which works just like Geometry Reader.

下面的代码将滚动到视图中的最后一项.我重用了您的代码,并添加了一些颜色,以实现更好的可视化效果.因此,我猜这是您的"Entry"结构:

The code below will scroll to the last item in your View. I reused your code adding some color for better visualisation. So this is your struct for 'Entry' I guess:

struct Entry {
    static var index = 0
    var name = "Entry number "
    
    func getName() -> String {
         Entry.index += 1
         return self.name + "\(Entry.index)"
    }
}

以及主要的ContentView:

And the main ContentView:

struct ContentView: View {
    let colors: [Color] = [.red, .blue, .green]
    var entries: [Entry] = Array(repeating: Entry(), count: 10)

    var body: some View {
        ScrollView {
            ScrollViewReader { value in
                            
                ForEach(0..<entries.count) { i in
                    Text(self.entries[i].getName())
                        .frame(width: 300, height: 200)
                        .background(colors[i % colors.count])
                        .padding(.all, 20)
                }
                .onAppear {
                    value.scrollTo(entries.count - 1, anchor: .center)
                }
            }
        }
    }
}

尝试在WWDC20宣布的新版SwiftUI中运行此命令.我认为这是一个很大的增强.

Try to run this in the new version of SwiftUI announced at WWDC20. I think it is a great enhancement.

这篇关于SwiftUI会自动滚动到ScrollView的底部(从下至上)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆