Scrollto with Scrollview doesn’t work the first time
Remove your VStacks as they are unnecessary and are interfering with the operation of the Scrollview
. Essentially, everything you are getting out of the ForEach
is a "cell". With the VStack's, you are putting EVERYTHING into 1 cell, and then expecting things to work. ScrollView
is looking for the multiple cells, so give them to it.
struct ContentView: View {
@State var sp = [1,2,3,4,5]
var body: some View{
VStack{
Text("asdf")
.frame(height: 90)
ScrollView{
ScrollViewReader{scrollReader in
ForEach(sp,id:\.self){p in
Text("\(p)").frame(height: 50)
}
Button("add"){
sp.append((sp.last ?? 0) + 1)
}
Spacer(minLength: 60)
.id("bottom")
.frame(maxWidth: .infinity)
.border(Color.green)
.onChange(of: sp.count){_ in
scrollReader.scrollTo("bottom")
}
}
}
.border(Color.black)
}
}
}
Since It does not work on the first time/click. So set a timer to execute your code again after a few milliseconds. I have set 100 milliseconds so that the ScrollView scrolls instantly.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mainScrollView.scrollTo(0,mainScrollView.getHeight());// Your code here
}
}, 100);// Delay time in milliseconds