How to add Tooltip on macOS 10.15 with SwiftUI

Viewed 887

According to Apple help modifier is only available in macOS11, so what is the workaround for adding a tooltip in macOS 10.15?

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.

REFERENCE

1 Answers

The workaround is to use a overplayed old NSView 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>) {
    }
}

public extension View {
    func toolTip(_ toolTip: String) -> some View {
        self.overlay(Tooltip(tooltip: toolTip))
    }
}

To use the modifier

            Image("pin")
                .resizable()
                .toolTip("TEST")

enter image description here

Also an open-source solution can be found on GitHub, https://github.com/quassummanus/SwiftUI-Tooltip

Related