SwiftUI:如何在悬停时显示工具提示/提示? [英] SwiftUI : How do you display a tooltip / hint on hover?

查看:43
本文介绍了SwiftUI:如何在悬停时显示工具提示/提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在某些视图上显示工具提示/提示?例如,在按钮上.

how to display tooltip / hint on some view? As example, on the button.

推荐答案

感谢 AndrewSorin 为解决方案方向.所提出的解决方案大多有效,但是当我使用它们时,它们完全弄乱了布局.事实证明,工具提示有自己的大小、框架等,它们不会自动匹配内容.

Thanks to both Andrew and Sorin for the solution direction. The presented solutions mostly worked but when I used them they totally messed up the layout. It turns out that the Tooltip has its own size, frame etc. which isn't automatically matching the content.

理论上我可以通过使用固定框架等来解决这些问题,但这对我来说似乎不是正确的方向.

In theory I could address those problems by using fixed frames etc. but that did not seem the right direction to me.

我提出了以下(稍微复杂一点)但易于使用的解决方案,没有这些缺点.

I have come up with the following (slightly more complex) but easy to use solution which doesn't have these drawbacks.

extension View {
    func tooltip(_ tip: String) -> some View {
        background(GeometryReader { childGeometry in
            TooltipView(tip, geometry: childGeometry) {
                self
            }
        })
    }
}

private struct TooltipView<Content>: View where Content: View {
    let content: () -> Content
    let tip: String
    let geometry: GeometryProxy

    init(_ tip: String, geometry: GeometryProxy, @ViewBuilder content: @escaping () -> Content) {
        self.content = content
        self.tip = tip
        self.geometry = geometry
    }

    var body: some View {
        Tooltip(tip, content: content)
            .frame(width: geometry.size.width, height: geometry.size.height)
    }
}

private struct Tooltip<Content: View>: NSViewRepresentable {
    typealias NSViewType = NSHostingView<Content>

    init(_ text: String?, @ViewBuilder content: () -> Content) {
        self.text = text
        self.content = content()
    }

    let text: String?
    let content: Content

    func makeNSView(context _: Context) -> NSHostingView<Content> {
        NSViewType(rootView: content)
    }

    func updateNSView(_ nsView: NSHostingView<Content>, context _: Context) {
        nsView.rootView = content
        nsView.toolTip = text
    }
}

我在工具提示的内容中添加了一个 GeometryReader,然后将工具提示的大小限制为与内容的大小相匹配.

I have added a GeometryReader to the content of the tooltip and then constrain the size of the Tooltip to the match the size of the content.

使用:

Toggle("...", isOn: $isOn)
   .tooltip("This is my tip")

这篇关于SwiftUI:如何在悬停时显示工具提示/提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆