gpt4 book ai didi

ios - 支持滑动以关闭表单中呈现的 UIViewControllerRepresentable

转载 作者:行者123 更新时间:2023-12-04 13:34:22 28 4
gpt4 key购买 nike

好像你用 UIViewControllerRepresentable当您通过 sheet 在您的 SwiftUI 应用程序中实现 View Controller 时您无法滑动以关闭它。您是否需要做一些事情来支持滑动以关闭?

struct ContentView: View {
@State var showingPicker = false

var body: some View {
Text("Hello, world!")
.onAppear {
showingPicker = true
}
.sheet(isPresented: $showingPicker, content: {
PHPicker() //cannot swipe to dismiss
//Text("Test") //can swipe to dismiss
})
}
}

struct PHPicker: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<PHPicker>) -> PHPickerViewController {
let config = PHPickerConfiguration()
return PHPickerViewController(configuration: config)
}

func updateUIViewController(_ uiViewController: PHPickerViewController, context: UIViewControllerRepresentableContext<PHPicker>) { }
}

最佳答案

可能的解决方案是添加类似 handle 的东西来拖动(没有样式 - 为演示简化),
demo

.sheet(isPresented: $showingPicker, content: {
VStack {
RoundedRectangle(cornerRadius: 8).fill(Color.gray)
.frame(width: 60, height: 8)
.padding(.top, 8)
PHPicker()
}
})
替代:解决方案是完全通过 UIKit 进行演示,只需在可表示的内部传递激活绑定(bind)。
这是可能的方法的演示。使用 Xcode 12.1/iOS 14.1 测试
demo2
struct PHPickerContentView: View {
@State var showingPicker = false

var body: some View {
Button("Picker") {
showingPicker = true
}
.background(PHPicker(isPresented: $showingPicker)) // << here !!
}
}

struct PHPicker: UIViewControllerRepresentable {
@Binding var isPresented: Bool

func makeUIViewController(context: Context) -> UIViewController {
UIViewController() // << picker presenter
}

func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
// react on binding & show if not shown
if isPresented && uiViewController.presentedViewController == nil {
let config = PHPickerConfiguration()
let picker = PHPickerViewController(configuration: config)
picker.delegate = context.coordinator

uiViewController.present(picker, animated: true)
picker.presentationController?.delegate = context.coordinator
}
}

func makeCoordinator() -> Coordinator {
Coordinator(self)
}

class Coordinator: NSObject, PHPickerViewControllerDelegate, UIAdaptivePresentationControllerDelegate {
let owner: PHPicker
init(_ owner: PHPicker) {
self.owner = owner
}

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {

// picked image handling code here

picker.presentingViewController?.dismiss(animated: true)
owner.isPresented = false // << reset on action !!
}

func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
owner.isPresented = false // << reset on swipe !!
}
}
}

关于ios - 支持滑动以关闭表单中呈现的 UIViewControllerRepresentable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63078836/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com