Home > Back-end >  Trying to implement custom functionality to a SwiftUI button, keep getting a warning
Trying to implement custom functionality to a SwiftUI button, keep getting a warning

Time:09-14

I am trying to make a custom button where I can implement my own functionality, like in the example below:

MSButton {
    print("hello")
}

Problem is, I keep getting the Expression of type '(() -> Void)?' is unused warning, and the functionality I add doesn't activate.

Here is the code I made in an attempt to implement this:

struct MSButton: View {
    
    var action: (() -> Void)?
    
    var body: some View {
        Button() {
            action // where I am getting the warning.
        } label: {
            Text("Button")
        }
    }
}

What am I missing that would allow me to get my action to work properly? Any help would be greatly appreciated.

CodePudding user response:

I was able to figure it out. My implementation is below:

struct MSButton: View {
    
    var action: (() -> Void)?
    
    var body: some View {
        Button() {
            self.action!() // fixed line
        } label: {
            Text("Button")
        }
    }
}

It works, although I don't understand exactly why this works, rather than the code I wrote in my question.

CodePudding user response:

The answer is quite simple, you forgot to call it as a function. Therefore, the correct answer is self.action?()

I personally would recommend to set it up like this

struct MSButton: View {
    var action: (() -> Void) = { }
    var body: some View {
        Button() {
            self.action()
        } label: {
            Text("Button")
        }
    }
}

CodePudding user response:

The issue is with the ? that makes the action optional and with how you are invoking the action.

Option 1

struct MSButton: View {
    
    var action: (() -> Void)?
    
    var body: some View {
        Button() {
            //Check if there is an action set
            if let action = action{
                action()
            }
        } label: {
            Text("Button")
        }
        //Safety measure so you dont have a button that looks like it has an action but doesn't
        .disabled(action == nil)
    }
}

Option 2

struct MSButton: View {
    //Remove the optional
    var action: () -> Void
    
    var body: some View {
        Button(action: action) {
            Text("Button")
        }
    }
}
  • Related