ios – How to access the properties of a parent function within a closure in Swift?


I’m new to Swift, and trying to do something I thought should be fairly simple.

I’m working through a class, and for the exercise code I have a view that I created called CustomButton:

import SwiftUI

struct CustomButton: View {

    // Define the variables for the label and action
    var buttonText: String
    var action: () -> Void


    var body: some View {
        // The button definition
        Button(action: {
            self.action()
        }, label: {
            Text(buttonText)
        })
        .padding()
        .border(.blue)
    }
}

CustomButton is called by the main view like this:

CustomButton(buttonText: "To Do", action: {
    todoList = dataService.getTodo()
    pageTitle = "To Do"
 })

This all works fine and is perfectly acceptable, but what I’d like to do is remove the redundant hardcoded pageTitle from the closure, and replace it with the buttonText variable from the outer function. Something like this:

CustomButton(buttonText: "To Do", action: {
    todoList = dataService.getTodo()
    pageTitle = CustomButton.buttonText
 })

When I try that, I get the error Instance member 'buttonText' cannot be used on type 'CustomButton'; did you mean to use a value of this type instead?

I also tried setting the pageTitle variable in the action of the CustomButton view, but that results in the error Cannot find pageTitle in scope error. I know there is a way to bind the variable between views, but I don’t know how to do that yet either. Seems like this should be pretty trivial, but it’s also been deceptively difficult to find a similar post to review in my searches online.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img