最佳答案
感谢两位 Andrew和 Sorin为解决方向。所提出的解决方案大多有效,但是当我使用它们时,它们完全弄乱了布局。事实证明,工具提示有自己的大小、框架等,它们不会自动匹配内容。
理论上,我可以通过使用固定框架等来解决这些问题,但这对我来说似乎不是正确的方向。
我提出了以下(稍微复杂一点)但易于使用的解决方案,它没有这些缺点。
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
到工具提示的内容,然后约束工具提示的大小以匹配内容的大小。要使用它:
Toggle("...", isOn: $isOn)
.tooltip("This is my tip")
关于tooltip - SwiftUI : How do you display a tooltip/hint on hover?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59129089/