我正在撰寫一個 SwiftUI 框架包,我希望在其中擁有一些允許呈現視圖的 API。對于這些視圖,我總是希望它們作為模態表視圖呈現在呈現視圖上方(我想禁止將這些視圖作為子視圖嵌入到應用程式的視圖中)。
Apple 似乎很少有這樣的系統 API,但我發現了這個 API——它的行為與我預期的一樣:
public func fileImporter(isPresented: Binding<Bool>, allowedContentTypes: [UTType], onCompletion: @escaping (_ result: Result<URL, Error>) -> Void) -> some View
https://developer.apple.com/documentation/swiftui/form/fileimporter(ispresented:allowedcontenttypes:allowsmultipleselection:oncompletion:)
請注意,Apple 已將此作為View擴展實作,因此您可以像這樣簡單地使用:
Button("Import..") {
self.showingFileImporter = true
}
.fileImporter(isPresented: $showingFileImporter, allowedContentTypes: [.pdf]) { result in
// got result
}
所以,我正在嘗試使用這種模式來實作我自己的 API,例如:
func mySomethingSelector(isPresented: Binding<Bool>, completion: @escaping () -> Void) -> some View
但是,我不確定如何開始實施。我注意到的第一件事是fileImporter實際回傳some View,但這不是實際呈現的螢屏。那么,我們需要回傳某種包裝視圖,然后呈現在包裝視圖之上?(請注意,我假設 Apple 實際上是fileImporter通過橋接到 UIKit 來實作的 - 并且可能超出了行程。但我只想使用標準的 SwiftUI 來實作我的實作)。
無論如何,希望這是有道理的。任何指導表示贊賞。
uj5u.com熱心網友回復:
一個非常簡單的實作可能如下所示,使用 asheet來顯示您的自定義View:
struct ContentView: View {
@State private var isPresented: Bool = false
var body: some View {
Button("Present") {
isPresented.toggle()
}
.mySomethingSelector(isPresented: $isPresented) {
print("Done")
}
}
}
extension View {
func mySomethingSelector(isPresented: Binding<Bool>, completion: @escaping () -> Void) -> some View {
self.sheet(isPresented: isPresented, onDismiss: completion) {
Text("My View")
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/533044.html
標籤:迅速设计模式迅捷
