Issue #617
On macOS 11, we can use .help
modifier to add tooltip
1 2
| Button() .help("Click here to open settings")
|
If you support macOS 10.15, then create empty NSView and use as overlay. Need to updateNSView
in case we toggle the state of tooltip
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import SwiftUI
struct Tooltip: NSViewRepresentable { let tooltip: String
func makeNSView(context: NSViewRepresentableContext<Tooltip>) -> NSView { let view = NSView() view.toolTip = tooltip return view }
func updateNSView(_ nsView: NSView, context: NSViewRepresentableContext<Tooltip>) { nsView.toolTip = tooltip } }
|
1 2 3 4 5 6
| Button(action: self.onGear) { Image("gear") .styleButton() } .overlay(Tooltip(tooltip: "Settings")) .buttonStyle(BorderlessButtonStyle())
|
Now we can add tooltip as a background. Before I used to add as overlay but that prevents interaction, even with .disabled(true)
1 2 3 4 5 6
| Button(action: self.onGear) { Image("gear") .styleButton() .background(ToolTip(tooltip: "Settings")) } .buttonStyle(BorderlessButtonStyle())
|
And we can even make an extension on View
to use tooltip easily
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import SwiftUI
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) public extension View { func toolTip(_ text: String) -> some View { return self .background( ToolTip(text) ) } }
Button(action: self.onGear) { Text("Click here") } .toolTip("Show statistics")
|
Updated at 2020-12-12 19:54:53