Repeating function in SwiftUI

Hello

Is there way to keep calling a function (efficiently) while the view is on screen, without using a timer, in SwiftUI?

Answered by workingdogintokyo in 679424022

you could try this:

struct ContentView: View {
    var body: some View {
        Text("keep calling a function").padding()
          .onAppear {
            callFunc()
          }
    }

    func callFunc() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            print("-----> callFunc")
            callFunc()
        }
    }
}
Accepted Answer

you could try this:

struct ContentView: View {
    var body: some View {
        Text("keep calling a function").padding()
          .onAppear {
            callFunc()
          }
    }

    func callFunc() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            print("-----> callFunc")
            callFunc()
        }
    }
}

so how to make it stop?

Here's how to make the loop stop:

By using a @State variable


struct ContentView: View {
    @State var stop: Bool = false
    
    var body: some View {
        Text("keep calling a function")
            .padding()
            .onAppear {
                callFunc()
            }
            .onTapGesture{
                if stop { //Continue loop
                    stop = false
                    callFunc()
                } else { //Stop loop
                    stop = true
                }
            }
    }
    
    func callFunc() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            print("-----> callFunc")
            if !stop {
                callFunc()
            }
        }
    }
}

Brendan Okey-Iwobi

Repeating function in SwiftUI
 
 
Q