Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading