1

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?

Taylor
  • 5,871
  • 2
  • 30
  • 64

1 Answers1

1

Probably you wanted modifier with attachmentAnchor, which allows to specify rect in holder view coordinates space, like

Rectangle()
    .frame(width: 100, height: 100, alignment: .leading)
    .popover(isPresented: $showPopover,
             attachmentAnchor: .rect(.rect(CGRect.zero)),   // << your rect here !!
             arrowEdge: .bottom) {               
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Documentation says "iOS ignores this parameter." See https://developer.apple.com/documentation/swiftui/path/popover(ispresented:attachmentanchor:arrowedge:content:) – Taylor Feb 02 '21 at 17:06
  • @Taylor it doesn't matter because popovers are not supported in iPhone iOS. its a bottom action sheet. however in iPadOS action sheets are different – CDM social medias in bio Aug 16 '22 at 12:37