SwiftUI Tooltips

How do I set the tooltip for an AppKit SwiftUI view?

Answered by mikepj in 613999022
In SwiftUI on macOS 11, you can use the .help("Tooltip text") view modifier to add a tooltip. See the "What's new in SwiftUI" session for WWDC 2020.
Accepted Answer

For the record there appears to be no native way to set a tooltip on a SwiftUI view (feedback #FB7095924), but the following workaround seems to do the trick:


public extension View {
    /// Overlays this view with a view that provides a toolTip with the given string.
    func toolTip(_ toolTip: String?) -> some View {
        self.overlay(TooltipView(toolTip))
    }
}

private struct TooltipView: NSViewRepresentable {
    let toolTip: String?

    init(_ toolTip: String?) {
        self.toolTip = toolTip
    }

    func makeNSView(context: NSViewRepresentableContext) -> NSView {
        let view = NSView()
        view.toolTip = self.toolTip
        return view
    }

    func updateNSView(_ nsView: NSView, context: NSViewRepresentableContext) {
    }
}

Thanks, this was helpful.


I was using Popovers but they have their own issues and seemed a little heavy. This is really clean and works well.

I get the following errors:


Type 'TooltipView' does not conform to protocol 'NSViewRepresentable'

Reference to generic type 'NSViewRepresentableContext' requires arguments in <...>

In SwiftUI on macOS 11, you can use the .help("Tooltip text") view modifier to add a tooltip. See the "What's new in SwiftUI" session for WWDC 2020.
19

so how do I use .help("Tooltip text") view

Works "as designed" in macOS app! Thanks for the tip/hint. :-)

SwiftUI Tooltips
 
 
Q