-
Notifications
You must be signed in to change notification settings - Fork 54
/
PopoverModifier.swift
36 lines (33 loc) · 1.31 KB
/
PopoverModifier.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import SwiftUI
struct PopoverModifier<PopView: View>: ViewModifier {
@Binding var isPresented: Bool
@State var sourceFrame: CGRect = .zero
var popView: () -> PopView
@State var popover: Popover?
func body(content: Content) -> some View {
WindowReader { window in
content
.frameReader(rect: { rect in
sourceFrame = rect
})
.onChange(of: isPresented) { newValue in
if newValue {
let popover = Popover(popView: AnyView(popView()), isPresented: $isPresented)
popover.context.sourceFrame = sourceFrame
popover.context.windowFrame = window?.bounds ?? .zero
popover.present(in: window)
self.popover = popover
} else {
guard let popover = popover else { return }
popover.dismiss()
}
}
#if !os(visionOS)
.onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
guard let popover = popover else { return }
popover.dismiss()
}
#endif
}
}
}