Swiftui Scrollview滚动至列表底部

Swiftui Scrollview滚动至列表底部,swift,swiftui,scrollview,Swift,Swiftui,Scrollview,每次添加新项目时,我都试图使视图滚动到项目列表的底部。 这是我的密码,有人能帮我吗 ScrollView(.vertical, showsIndicators: false) { ScrollViewReader{ value in VStack() { ForEach(0..<self.count, id:\.self) {

每次添加新项目时,我都试图使视图滚动到项目列表的底部。 这是我的密码,有人能帮我吗

ScrollView(.vertical, showsIndicators: false) {
                ScrollViewReader{ value in
                    VStack() {
                        ForEach(0..<self.count, id:\.self) {
                            Text("item \($0)")
                        }
                    }.onChange(of: self.data.sampleCount, perform: value.scrollTo(-1))
                }
            }
ScrollView(.vertical,showsIndicators:false){
ScrollViewReader{中的值
VStack(){

ForEach(0..我们需要为
ScrollView
中要滚动到的视图提供
id

这是一个解决方案的演示。使用Xcode 12.1/iOS 14.1进行了测试

struct DemoView:View{
@国家私有变量数据=[String]()
var body:一些观点{
VStack{
按钮(“添加”){data.append(“data\(data.count+1)”)}
.padding().border(颜色.蓝色)
滚动视图(.vertical,showsIndicators:false){
ScrollViewReader{sr in
VStack{
ForEach(self.data.index,id:\.self){
文本(“项目\($0)”)

.padding().id($0)//ios13怎么样?
struct DemoView: View {
    
    @State private var data = [String]()

    var body: some View {
        VStack {
            Button("Add") { data.append("Data \(data.count + 1)")}
                .padding().border(Color.blue)
                
            ScrollView(.vertical, showsIndicators: false) {
                ScrollViewReader{ sr in
                    VStack {
                        ForEach(self.data.indices, id:\.self) {
                            Text("item \($0)")
                                .padding().id($0)     // << give id
                        }
                    }.onChange(of: self.data.count) { count in
                        withAnimation {
                            sr.scrollTo(count - 1)   // << scroll to view with id
                        }
                    }
                }
            }
        }
    }
}