Created
September 15, 2021 06:25
-
-
Save fatbobman/d248d80d8d1a23b5f8d84ed7544d2ae3 to your computer and use it in GitHub Desktop.
SwiftUI interactiveDismissDisabled extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
saved my life, thank you