Issue #617
On macOS 11, we can use .help
modifier to add tooltip
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
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
}
}
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)
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
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")