Post

Replies

Boosts

Views

Activity

How to create an auto-scrollable Text view?
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!
1
0
579
Dec ’21
How to redraw a child view in SwiftUI?
I have a ContentView that has a state variable "count". When its value is changed, the number of stars in the child view should be updated. struct ContentView: View {   @State var count: Int = 5       var body: some View {     VStack {       Stepper("Count", value: $count, in: 0...10)       StarView(count: $count)     }     .padding()   } } struct StarView: View {   @Binding var count: Int       var body: some View {     HStack {       ForEach(0..<count) { i in         Image(systemName: "star")       }     }   } } I know why the number of stars are not changed in the child view, but I don't know how to fix it because the child view is in a package that I cannot modify. How can I achieve my goal only by changing the ContentView?
2
0
393
Sep ’21