简体   繁体   English

SwiftUI:如何为所有按钮添加onHover

[英]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?这是针对 macOS 的,如何在扩展中添加 onHover 以便它适用于我应用程序中的每个 Button?

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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