Home > OS >  Struggling with creating extension for Button in SwiftUI
Struggling with creating extension for Button in SwiftUI

Time:04-16

I have been trying to make an extension that would change how a button is created, but with no luck.

The usual way of making a button would be like this:

Button {
    print("pressed")
} label: {
    Label("Button", systemImage: "person")
}

However I would like to be able to create buttons like this:

Button("Button", systemImage: "person") {
    print("pressed")
}

Is this possible? If so, how? Any help would be greatly appreciated.

CodePudding user response:

The main non-obvious part in this issue is to confirm and align generics of new custom init in extension with one used in SwiftUI Button, because of used same name Label for different things.

Here is a main part of found solution:

init(_ title: LocalizedStringKey, systemImage: String, action: @escaping () -> Void) 
     where Label == SwiftUI.Label<Text, Image> {

Complete findings and solution is here

  • Related