Skip to content

Instantly share code, notes, and snippets.

@fatbobman
Created September 15, 2021 06:25
Show Gist options
  • Save fatbobman/d248d80d8d1a23b5f8d84ed7544d2ae3 to your computer and use it in GitHub Desktop.
Save fatbobman/d248d80d8d1a23b5f8d84ed7544d2ae3 to your computer and use it in GitHub Desktop.
SwiftUI interactiveDismissDisabled extension
import SwiftUI
import UIKit
struct SetSheetDelegate: UIViewRepresentable {
let delegate:SheetDelegate
init(isDisable:Bool,attempToDismiss:Binding<UUID>){
self.delegate = SheetDelegate(isDisable, attempToDismiss: attempToDismiss)
}
func makeUIView(context: Context) -> some UIView {
let view = UIView()
return view
}
func updateUIView(_ uiView: UIViewType, context: Context) {
DispatchQueue.main.async {
uiView.parentViewController?.presentationController?.delegate = delegate
}
}
}
final class SheetDelegate: NSObject, UIAdaptivePresentationControllerDelegate {
var isDisable: Bool
@Binding var attempToDismiss: UUID
init(_ isDisable: Bool, attempToDismiss: Binding<UUID> = .constant(UUID())) {
self.isDisable = isDisable
_attempToDismiss = attempToDismiss
}
func presentationControllerShouldDismiss(_ presentationController: UIPresentationController) -> Bool {
!isDisable
}
func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) {
attempToDismiss = UUID()
}
}
public extension View{
func interactiveDismissDisabled(_ isDisable:Bool,attempToDismiss:Binding<UUID>) -> some View{
background(SetSheetDelegate(isDisable: isDisable, attempToDismiss: attempToDismiss))
}
}
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self.next
while parentResponder != nil {
if let viewController = parentResponder as? UIViewController {
return viewController
}
parentResponder = parentResponder?.next
}
return nil
}
}
struct ContentView: View {
@State var sheet = false
var body: some View {
VStack {
Button("show sheet") {
sheet.toggle()
}
}
.sheet(isPresented: $sheet) {
SheetView()
}
}
}
struct SheetView: View {
@State var disable = false
@State var attempToDismiss = UUID()
var body: some View {
VStack {
Button("disable: \(disable ? "true" : "false")") {
disable.toggle()
}
.interactiveDismissDisabled(disable, attempToDismiss: $attempToDismiss)
}
.onChange(of: attempToDismiss) { _ in
print("try to dismiss sheet")
}
}
}
@Fercomp
Copy link

Fercomp commented Apr 17, 2023

saved my life, thank you

@fatbobman
Copy link
Author

saved my life, thank you

😃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment