How to make tooltip in SwiftUI for macOS

Issue #617

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())

Sometimes it’s better to add overlay tooltip to Image inside Button to avoid blocking

1
2
3
4
5
6
Button(action: self.onGear) {
Image("gear")
.styleButton()
.overlay(Tooltip(tooltip: "Settings"))
}
.buttonStyle(BorderlessButtonStyle())

Comments