I want to create an auto-scrollable text. When the content grows longer, it can automatically scroll to the bottom and show the last line.
Here is my code:
struct ContentView: View {
@State var text = "Hello everyone: "
@State var index = 0
var body: some View {
VStack {
ScrollViewReader { reader in
ScrollView {
VStack {
Text(text)
.font(.title)
.id("textId")
.padding(10)
}
}
.frame(width: 300, height: 160, alignment: .topLeading)
.border(.blue)
.onChange(of: text, perform: { _ in
reader.scrollTo("textId", anchor: .bottom)
})
}
Button("Append") {
index += 1
text += "Hello \(index); "
}
}
}
}
It only works when I scroll the text and then append new text.
Can someone please help? Thank you!