I want to toggle a Boolean state when a view is visible in the phone screen.
I’ve made the LazyHStack as below however, the following 2 views, somehow is already appeared. I tried using the new API onScrollVisibilityChange(threshold: 1,..)
and the result is the same.
How can I just make sure that only the right view turns true ?
import SwiftUI
let quotes: [String] = [
"11 Life is full of possibilities You just need to know where to look.",
"22 The only thing predictable about life is its unpredictability",
"33 You and I are a team. Nothing is more important than our friendship.",
"44 I don’t care what they’re going to say. Let the storm rage on. The cold never bothered me anyway.",
"55 When you’re curious, you find lots of interesting things to do."
]
struct TryScrollView: View {
var body: some View {
ScrollView(.horizontal) {
LazyHStack(spacing: 0) {
ForEach(quotes, id: .self) { quote in
TestView(text: quote)
}
}
}
.scrollTargetBehavior(.paging)
}
}
struct TestView: View {
@State var isVisible: Bool = false
let text: String
var body: some View {
VStack {
Text(text)
.foregroundStyle(.white)
.font(.system(.title))
.padding()
.background(
RoundedRectangle(cornerRadius: 5)
.fill(.blue)
)
}
.frame(width: 320, alignment: .leading)
.padding(24)
.onScrollVisibilityChange(threshold: 1, { visible in
print("(text) is visible") //--> I want to toggle isVisible here
})
.onAppear {
print("(text) appears") //--> I want to toggle isVisible here
}
}
}
#Preview {
TryScrollView()
}