Popovers icon indicating copy to clipboard operation
Popovers copied to clipboard

How to dismiss popover when click source view

Open maxwellyue opened this issue 1 year ago • 6 comments

Button("Present popover!") {
   // how to make this 'toggle' working ???
    present.toggle()
}
.popover(present: $present) { 
    Text("Hi, I'm a popover.")
}

When popover is presented, If I click this button again, I want it to dismiss this popover. But in fact, it first dismiss then present again. So how to make this 'toggle' button working?

maxwellyue avatar Sep 17 '22 08:09 maxwellyue

I have found that using the following works for me.

This will dismiss the popover by tapping outside $0.dismissal.mode = .tapOutside

I have also set an auto dismissal like this: You would attach this onAppear to the popover view .onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: { showPopoverHint.toggle() }) }

All this works for me.

tazmancoder avatar Nov 09 '22 13:11 tazmancoder

Rendering a GeometryReader as a background of the Button and making the popover a modifier of a Spacer in the GeometryReader and setting its excludedFrames to contain the GeometryReader's frame in the .global coordinate space did the trick for me

Button("Present popover!") {
    present.toggle()
}
.background(
    GeometryReader { geometry in
        Spacer()
            .popover(present: $present, attributes: { attributes in
                attributes.dismissal.excludedFrames = {
                    return [geometry.frame(in: .global)]
                }
            }, view: {
                Text("Hi, I'm a popover.")
            })
    }
)

raysarebest avatar Dec 22 '22 01:12 raysarebest

This needs to be a lib function but thank you for the creative solution!

aehlke avatar Jan 08 '23 01:01 aehlke

Nice idea and fix, thanks. Will see what I can do

aheze avatar Jan 08 '23 01:01 aheze

Unfortunately I can't find a working solution for accomplishing this with List items and popovers activated by selection, because List first removes the selection before adding it again. I'm now doing it by detecting extremely quick close/reopen on the same item.

aehlke avatar Jan 08 '23 03:01 aehlke

Button("Present popover!") {
    present.toggle()
}
.allowsHitTesting(!present)
.popover(present: $present) { 
    Text("Hi, I'm a popover.")
}

😂

whuxujiyuan avatar Dec 12 '23 07:12 whuxujiyuan