SwiftUI - How can I call a Function in my View?

Viewed 15163

I am using SwiftUI/Swift for a week now, and I love it. Now I have a problem. I want to call a Function from my View, but I get this Error

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

This is the Code:

struct testView: View {
    
    
    var body: some View {
        VStack {
            Text("TextBox")
            Text("SecondTextBox")
            self.testFunction()
        }
    }
    
    func testFunction() {
        print("This is a Text.")
    }
    
}

I don't get it. In other languages its much simpler and could work that way. Can anybody help me please? Swift is pretty new to me :D

3 Answers

Meanwhile here are the places (not all) where/how you can call a function

    init() {
        self.testFunction()     // non always good, but can
    }

    var body: some View {
        self.testFunction()            // 1)
        return VStack {
            Text("TextBox")
               .onTapGesture {
                  self.testFunction()    // 2)
               }
            Text("SecondTextBox")
        }
        .onAppear {
            self.testFunction()     // 3)
        }
        .onDisappear {
            self.testFunction()     // 4)
        }
    }

... and so on

Using Swift 5.3 and Xcode 12.4

I use a little extension to debug inside the Views (VStack in the example), e.g. to inspect a geometryReader.size. It could be used to call any function in the View as follows:

NOTE: For debugging purposes only. I don't recommend including code like this in any production code

VStack {
    Text.console("Hello, World")
    Text("TEXT"
}

extension Text {
    static func console<T>(_ value: T) -> EmptyView {
        print("\(value)")
        return EmptyView()
    }
}

This will print "Hello, World" to the console.....

There is a reason, when writing in swift UI (iOS Apps), that there is a View protocol that needs to be followed. Calling functions from inside the structure is not compliant with the protocol.

The best thing you can do is the .on(insertTimeORAction here).

Read more about it here

Related