I'm working with a ScrollView
to manage the display of a text in my View
.
ScrollView
should stretch according to the Text
. How can I do this?I tried a few attempts which you can see here in my example.
ScrollView
to be non-scrollable when the text is not long. How can I solve these two problems?struct Test2: View {
@State private var contentSize: CGSize = .zero
var body: some View {
ZStack {
Color.blue
.ignoresSafeArea()
VStack {
ScrollView {
Text ("This is a test textThis is a test texThis is a test texThis is a test")
.padding()
.overlay {
GeometryReader { geo in
Color.clear.onAppear {
contentSize = geo.size
}
}
}
}
}
.background(.white)
.frame(maxHeight: contentSize.height)
}
}
}
The ScrollView already seems to resize to fit the text when it appears, but if you need to change the text content after it appears, try adding this in the GeometryReader to update the size when it changes:
Color.clear.onChange(of: text) {
newText in
contentSize = geo.size
}
You would need a variable for the text though.
@State private var text: String = "This is a test textThis is a test texThis is a test texThis is a test"
(replace Text("This is...")
with Text(text)
)
scrollDisabled
that updates when the text changes/appears.Underneath contentSize
:
@State private var cantScroll: Bool = true
Embed ZStack in GeometryReader (GeometryReader { viewGeo in...
), then
add code to check and compare view sizes whenever contentSize
updates:
if contentSize.height > viewGeo.size.height {
cantScroll = false
} else {
cantScroll = true
}
And finally, modify ScrollView:
.scrollDisabled(cantScroll)
Final code:
struct Test2: View {
@State private var contentSize: CGSize = .zero
@State private var text: String = "This is a test textThis is a test texThis is a test texThis is a test"
@State private var cantScroll: Bool = true
var body: some View {
GeometryReader { viewGeo in
ZStack {
Color.blue
.ignoresSafeArea()
VStack {
ScrollView {
Text(text)
.padding()
.overlay {
GeometryReader { geo in
Color.clear.onAppear {
contentSize = geo.size
if contentSize.height > viewGeo.size.height {
cantScroll = false
} else {
cantScroll = true
}
}
Color.clear.onChange(of: text) {
_ in
contentSize = geo.size
if contentSize.height > viewGeo.size.height {
cantScroll = false
} else {
cantScroll = true
}
}
}
}
}
.scrollDisabled(cantScroll)
}
.background(.white)
.frame(maxHeight: contentSize.height)
}
}
}
}
I hope this helps.