Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI: How to add onHover to all buttons

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 {
//
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading