iosswiftxcodeswiftuiviewbuilder

Passing a String value to a viewbuilder from another view


This is the Base View

struct BaseView<Content: View>: View {
    @State private var ShowSFView : Bool = false
   
    let content: Content
   
    init(@ViewBuilder content:  () -> Content ) {
        self.content = content()
     
        
    }

//Code for button and URL

}

I need to pass two String values to this BaseView , from another View when I call this baseView. One is for button label and other one for URL.

I'am unable to do it from declaring variables on initialiser, getting various errors. How can a i achieve this?

Edit

Initialiser in baseView

init(@ViewBuilder content:  () -> Content , btnlabel: String) {
        self.content = content()
        self.btnlabel=btnlabel
        
    }

How I called it from another View

 BaseView.init(content: () -> _, btnlabel: "")

Solution

  • You can pass any parameter or string parameter the same as normal init.

    struct BaseView<Content: View>: View {
        
        @State private var ShowSFView : Bool = false
        
        private let content: Content
        
        let stringOne: String
        let stringTwo: String
        
        init(stringOne: String, stringTwo: String, @ViewBuilder content:  () -> Content ) {
            self.content = content()
            self.stringOne = stringOne
            self.stringTwo = stringTwo
        }
        
        var body: some View {
            Text(stringOne)
            Text(stringTwo)
        } 
    }
    

    Now you can use it like

    BaseView(stringOne: "str1", stringTwo: "str2") {
        // Content
    }
    

    EDIT

    From your example, you can use it like

    BaseView(content: {
        // Content
    }, btnlabel: "Lable")