SwiftUI: How to add onHover to all buttons

128 Views Asked by At

This is for macOS, how to add onHover in the extension so that it applies to every Button in my app?

Button("Hello World") {
    print("Hello World")
   }
   .onHover { inside in
     if inside {
         NSCursor.pointingHand.push()                     
                 } else {
              NSCursor.pop()
                }
             }


extension Button {
//
}
1

There are 1 best solutions below

0
lorem ipsum On BEST ANSWER

You can "override" the default implementations with a "Project" version.

//Name `struct` Button
struct Button: View{
    let title: LocalizedStringKey
    let action: () -> Void
    
    init(_ title: LocalizedStringKey, action: @escaping () -> Void) {
        self.title = title
        self.action = action
    }
    var body: some View{
        //Uses SwiftUI version of button
        SwiftUI.Button(title, action: action)
            .onHover { inside in
                if inside {
                    NSCursor.pointingHand.push()
                } else {
                    NSCursor.pop()
                }
            }
    }
}

The example above will replace all the instances of

public init(_ titleKey: LocalizedStringKey, action: @escaping () -> Void)