我刚刚开始学习 swiftui,我试图弄清楚如何在单击单词时重新创建以下弹出窗口:
我想要重新创建的是每当单击特定单词时,能够在特定单词的正下方或上方弹出这种弹出窗口。
这个功能在 swiftui 中是如何调用的?现在我最好的猜测是它使用一个菜单,单击它时调用一个函数,然后显示弹出窗口,该弹出窗口经过定制,使其看起来像现在一样。这是正确的吗?
如果没有,您能给我指出此功能的正确文档或名称吗?
该组件也称为 PopTip,在 UIKit 中非常流行。在 SwiftUI 中,您只需设置一个变量来显示和隐藏弹出窗口即可实现:
@State var isInfoPopTipShown: Bool = false
在 var body 中:一些 View {} 创建一个图标视图:
private var iconView: some View {
Image(systemName: "info.circle.fill")
.resizable()
.scaledToFit()
.frame(width: 24, height: 24)
.foregroundStyle(.purple)
}
然后使用上面的 iconView 创建一个按钮并探索 .popover(...) 的好处:
popover(isPresented:绑定,attachmentAnchor: PopoverAttachmentAnchor = .rect(.bounds), arrowEdge: Edge = .top, @ViewBuilder内容:@escaping() -> Content) -> 一些View在哪里 内容:查看
Button {
isInfoPopTipShown.toggle()
} label: {
iconView
.popover(isPresented: self.$isInfoPopTipShown,
attachmentAnchor: .point(.top),
arrowEdge: .top,
content: {
VStack {
Text("Coder get your stuff and")
Text("let's have fun!!")
}
.multilineTextAlignment(.center)
.lineLimit(0)
.foregroundStyle(.black)
.font(.system(size: 20, weight: .semibold, design: .rounded))
.padding()
.presentationCompactAdaptation(.none)
})
}
要复制的完整代码这里