#modifier
The onAppear and onDisappear modifiers are extremely convenient methods that let us call functions when specific components appear or disappear from the screen. These are often used for managing animations and loading data in SwiftUI applications.
Create a nav stack with string var
struct ContentView: View {
@State var myText: String = "String"
var body: some View {
NavigationStack{
ScrollView{
Text(myText)
}
.navigationTitle("onAppear Modifier")
} // END: NAV
}
}
Add onAppear Modifier
ScrollView{
Text(myText)
}
.onAppear(perform: {
myText = "This is the new text!"
})
myText var value gets changed, because we are watching the screen.
Add a delay to modifier
ScrollView{
Text(myText)
}
.onAppear(perform: {
DispatchQueue.main.asyncAfter(deadline: .now() + 5)
{ myText = "This is the new text!"}
})
We can add dispatchQueue to make .onAppear modifier works after 5 seconds.
onDisappear
.onDisappear(perform: {
myText = "Ending Text."
})
onDisappear won’t be shown, because modifier works after user leaves the screen.
Usually to clear the function that aren’t visible is the main purpose of this modifier.
Adding a lazy V Stack
for the larger data set, it’s smarter to use the lazy stack.
LazyVStack{
ForEach(0..<50) { _ in
RoundedRectangle(cornerRadius: 25)
.frame(height:200)
.padding()
.onAppear{
}
}
}
by writing .onAppear{}
we can skip the perform part.
@State var count: Int = 0
.onAppear{ count +=1 }