How I can extend a View in SwiftUI?

Viewed 536

I made a View called customText, you can see the codes down. I am using customText inside my ContentView. I want to give extra Possibility to my customText in this way that I want extend this View with Special command, that command or function would be called .stringOfText().

My Goal: For giving light what I am looking for: I want be able to type this code in my ContentView:

struct ContentView: View {
    var body: some View {

        customText().stringOfText("Omid")

    }
}

PS: I know that I can send that data with @Binding or many other ways! but I am interested to the way I mentioned at my Goal.

struct ContentView: View {
    
    var body: some View {

        customText()
  
    }
}

struct customText: View {
    
    @State var stringOfText = "Hello, world!"
    
    var body: some View
    {
        Text(stringOfText)
    }
}
2 Answers

You probably want this extension:

extension customText {
    func stringOfText(_ text: String) -> customText {
        customText(stringOfText: text)
    }
}

I was very confused about this. This is how I rewrote to make more clear what is happening:

struct ContentView: View {
    var body: some View {
        customText().stringFunc("Omid")
    }
}

struct customText: View {
    @State var stringVar = "Hello, world!"
    var body: some View
    {
        Text(stringVar)
    }
}

extension customText {
    func stringFunc(_ newstring: String) -> customText {
        customText(stringVar: newstring)
    }
}

This seems to create an instance of customText() in the ContentView. The "stringVar" will by default be set to "Hello, world!".

Then, the method "stringFunc()" of this instance will be called to create a new instance of customText() and the "stringVar" variable will directly be set to "Omid" in the new instance.

So, two instances of customText() will be created in one line.

Can that be the real intent?

Related