如何通过单击按钮SwiftUI iOS 13滚动到ScrollView的底部

问题描述

我知道这已在iOS 14中解决,但我当前的项目在iOS 13中,我们必须快速发布它。我尝试了多种方法,但是没有运气。我只想单击一个按钮并滚动到ScrollView的底部,就这样。令我惊讶的是,SwiftUI中没有内置函数!!!

struct ContentView: View {
var items = [Color.red,Color.orange,Color.yellow,Color.green,Color.blue,Color.purple,Color.red,Color.purple]

var body: some View {
    ZStack {
        ScrollView(Axis.Set.vertical,showsIndicators: false) {
            vstack {
                ForEach(self.items,id: \.self) { item in
                    // 3.
                    Circle()
                        .fill(item)
                        .frame(width: 100,height: 100)
                }
            }
        }
        
        vstack {
            Spacer()
            HStack {
                Spacer()
                Button(action: {
                    // scroll to bottom
                }) {
                    Text("Button")
                }
            }
            .padding(.trailing,20)
            .padding(.bottom,20)
            
        }
        
    }
    
}
}

如果有人可以帮助

解决方法

经过几个小时的搜索,我发现了这个惊人的 library,它完全符合您的要求

ScrollView{ proxy in
            Button("click"){
                proxy.scrollTo(200)
            }.foregroundColor(.red)
            ForEach(0..<1000){ index in
                Text("\(index)")
                    .scrollId(index)
            }
        }