Skip to content

Instantly share code, notes, and snippets.

@codelynx
Created June 13, 2024 02:25
Show Gist options
  • Save codelynx/d2bf83735c3bfb75bdbe870b72983bfd to your computer and use it in GitHub Desktop.
Save codelynx/d2bf83735c3bfb75bdbe870b72983bfd to your computer and use it in GitHub Desktop.
SwiftUI Button to present popover with your content
//
// PopoverButtonView.swift
//
// Created by Kaz Yoshikawa on 2024/06/12.
//
import SwiftUI
/**
`PopoverButtonView` is a reusable SwiftUI view that displays a button, which presents a popover when tapped.
The view is highly customizable, allowing you to specify any type of view for both the button's label and the popover's content.
Usage:
PopoverButtonView(label: {
Text("Show Popover")
}, popoverContent: {
Text("This is the popover content")
.padding()
})
.padding()
- Parameters:
T: The type of view to be used as the button's label.
U: The type of view to be used as the popover's content.
- Note:
- The `isPresentingPopover` state variable controls the presentation of the popover.
- The `label` and `popoverContent` closures provide the views for the button's label and popover content, respectively.
*/
struct PopoverButtonView<T: View, U: View>: View {
@State private var isPresentingPopover = false
let label: () -> T
let popoverContent: () -> U
init(label: @escaping () -> T, popoverContent: @escaping () -> U) {
self.label = label
self.popoverContent = popoverContent
}
var body: some View {
Button(action: { self.isPresentingPopover.toggle() }) {
self.label()
}
.popover(isPresented: $isPresentingPopover) {
self.popoverContent()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment