Reputation: 1356
I am using SwiftUI 2's new TextEditor. What I'd like to do is the TextEditor to scroll to top automatically when it's text changes which currently is not the case.
Here's the example project's code:
import SwiftUI
struct ContentView: View {
@State private var text: String = Self.text1
static private var text1 = """
Text 1:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
static private var text2 = """
Text 2:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
var body: some View {
VStack {
TextEditor(text: $text)
.frame(maxHeight: 150)
Button("Toggle Text") {
if text == Self.text1 {
text = Self.text2
} else {
text = Self.text1
}
}
}
}
}
I found a few threads concerning ScrollView that did not help, couldn't find anything on TextEditor though.
Upvotes: 2
Views: 1261
Reputation: 8517
Here is a possible solution using ScrollViewReader for SwiftUI 2.0 and ScrollView
var body: some View {
ScrollViewReader { sp in
ScrollView {
TextEditor(text: $text)
.id(0)
}.frame(maxHeight: 150)
Button("Toggle Text") {
if text == Self.text1 {
text = Self.text2
sp.scrollTo(0, anchor: .top)
} else {
text = Self.text1
sp.scrollTo(0, anchor: .top)
}
}
}
}
Upvotes: 2