Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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")
}
}
}
@fatbobman

This comment has been minimized.

Copy link
Owner Author

@fatbobman fatbobman commented Sep 15, 2021

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