简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM