I have a rect which represents what the user has selected in a document. I'd like to show a popover positioned relative to the rect using SwiftUI. In UIKit, this would be accomplished using UIPopoverPresentationController.sourceRect
.
I tried the following:
struct ContentView: View {
@State var selectionBounds = CGRect(x: 100, y: 100, width: 100, height: 100)
@State var showPopover = false
var body: some View {
ZStack {
Path { path in
path.addRect(selectionBounds)
}
.stroke(lineWidth: 1.0)
.popover(isPresented: $showPopover) {
Text("Popover")
}
Button(action: { showPopover = true }, label: {
Text("Show Popover")
})
}
}
}
The rect is drawn in the correct position, but the popover doesn't show.
So I tried using a Rectangle
instead of Path
:
Rectangle()
.frame(width: 100, height: 100, alignment: .leading)
.position(x: 100, y: 100)
.popover(isPresented: $showPopover) {
Text("Popover")
}
This only shows the popover if position
is omitted. Using offset
instead will anchor the popover relative to the non-offset position of the Rectangle
.
How can I anchor a popover relative to a CGRect?