Home > Net >  SwiftUI Popover Attachment Anchor Offset From Trailing Edge
SwiftUI Popover Attachment Anchor Offset From Trailing Edge

Time:06-23

Context:

In SwiftUI on macOS 12.0, I'm showing a Popover like this:

enter image description here

Button {
   isShowingFilterPopover.toggle()
} label: {
   ...
}
.buttonStyle(.plain)
.popover(isPresented: $isShowingFilterPopover, attachmentAnchor: .point(.bottomTrailing), arrowEdge: .bottom, content: { ... })

Question:

I would like to tell SwiftUI to anchor this popover 8 points to the left of the button's .bottomTrailing location.

I know that I can specify an exact point as an offset from the button, like this:

attachmentAnchor: .rect(.rect(CGRect(x: 70, y: 15, width: 0, height: 0)))

But that works from the leading (left) edge button's frame and I need to work from its trailing (right) edge. Reason: the button's text ("All Entries") dynamically changes to show whatever search term the user enters, which means the width of the button changes. Working from the leading edge with a constant offset is therefore not possible.

So, how do I tell SwiftUI to anchor the popover 8 points to the left of the button's trailing edge?

CodePudding user response:

Just give a 8px smaller view for popover, and everything else will happen automatically.

Here is a demo. Tested with Xcode 13.4 / macOS 12.4

demo

Button { self.isPop.toggle() }
    label: { Text("Pop").padding() }
    .buttonStyle(.plain)
    .padding(.horizontal, -8)          // << here !!
    .popover(isPresented: $isPop,
             attachmentAnchor: .point(.bottomTrailing),
             arrowEdge: .bottom) { ... }
    .padding(.horizontal, 8)
  • Related