SwiftUI:如何在悬停时显示工具提示/提示?

编程入门 行业动态 更新时间:2024-10-25 06:30:46
本文介绍了SwiftUI:如何在悬停时显示工具提示/提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

推荐答案

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

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:如何在悬停时显示工具提示/提示?

本文发布于:2023-11-22 23:24:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619321.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:提示   工具   如何在   SwiftUI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!