swiftuipopoveranchorpoint

SwiftUI: Offset Popover Anchor by Constant Amount



NOTE: This is a macOS question, not iOS.


I would like to anchor a SwiftUI Popover exactly 70 points to the right of the bottom-leading corner of the "20 Hours Ago" button in this image:

enter image description here

I do NOT want to anchor the popover a certain percentage of the button's width (which would be using UnitPoint). The button's text is updated as the user selects different items in the popover and as the button's width changes, the percentage-based anchor point moves, causing the popover to jump around horizontally. No good. I also don't want to anchor the popover exactly at the bottom-leading corner, as that looks dumb.

The trouble is, I can't figure out what to feed SwiftUI to get a constant, simple horizontal offset for the anchor point of the popover. I'm here:

.popover(isPresented: $isShowingPopover, attachmentAnchor: .point(.bottomLeading), arrowEdge: .bottom, content: {
    ...
})

How do I specify: "start at the bottom-leading point and then go 70 points to the right"? (Based on the strings that will appear in the button, I KNOW 70 is a good-looking anchor point for all cases.)


Solution

  • You can use .rect:
    That defines absolute offsets to the parent content rect, but then you'll have to specify y offset as well.

    .popover(isPresented: $show1,
             attachmentAnchor: .rect(.rect(CGRect(x: 70, y: 15, width: 0, height: 0))),
             arrowEdge: .bottom)
    {
         Text("Popover")
             .frame(width: 200, height: 100)
    }