简体   繁体   中英

How to add Tooltip on macOS 10.15 with SwiftUI

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

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

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM