Search code examples
swiftbuttonswiftuiaction

How to access a Button's titleLabel from inside it's action in SwiftUI?


Very simply, if I am declaring a button like:

Button("buttonLabel") {
    //How do I access the titleLabel.text, in this case "buttonLabel" inside the button's action?
}

Side Note: If I can add anything to contextualize this, I can, but I feel like there must be some super simple way to access the label...


Solution

  • You could access it by declaring it as a variable outside body as a member of the ContentView:

    struct ContentView: View {
        let buttonLabel = "buttonLabel"
    
        var body: some View {
            Button(buttonLabel) {
                print("Pressed \(self.buttonLabel)")
            }
        }
    }
    

    If your requirement is to check/modify the button text then here is an example:

    struct ContentView: View {
        @State var buttonLabel = "Tap me!"
    
        var body: some View {
            Button(buttonLabel) {
                self.buttonLabel = self.buttonLabel == "Tap me!" ? "I was tapped!" : "Tap me!"
            }
        }
    }