我打算让用户使用 PhotosPicker 和 CoreData 将照片添加/保存到我的(iOS 15 及更高版本)应用程序中,但我遇到了一些麻烦。
PhotosPickerItem
仅在 iOS 16 中可用,因此 Xcode 建议我在表单视图上方使用 @available(iOS 16, *)
,我还必须从内容视图中使用 if #available(iOS 16, *) {
检查 iOS 版本。它看起来像这样:
// ContentView.swift
import SwiftUI
struct ContentView: View {
@State var showForm = false
var body: some View {
Button("Create a new item", action: { showForm = true })
.fullScreenCover(isPresented: $showForm, content: { if #available(iOS 16.0, *) { FormView() } })
}
}
// FormView.swift
import SwiftUI
import PhotosUI
@available(iOS 16.0, *)
struct FormView: View {
@State var selectedItem: PhotosPickerItem? = nil // iOS 16 only
var body: some View {
PhotosPicker("Add a photo", selection: $selectedItem, matching: .images, photoLibrary: .shared())
// Some lines of code for the PhotosPicker
}
}
但是 iOS 15 用户无法访问
FormView()
,我想知道我该怎么办?我的猜测是复制表单视图并复制/粘贴其中的所有内容,除了关于添加/保存照片功能的代码行。但这似乎真的很荒谬。它看起来像这样:
// ContentView.swift
import SwiftUI
struct ContentView: View {
@State var showForm = false
var body: some View {
Button("Create a new item", action: { showForm = true })
.fullScreenCover(isPresented: $showForm, content: { if #available(iOS 16.0, *) { FormView() } else { FormViewBis() } })
}
}
// FormView.swift
import SwiftUI
import PhotosUI
@available(iOS 16.0, *)
struct FormView: View {
@State var selectedItem: PhotosPickerItem? = nil // iOS 16 only
var body: some View {
PhotosPicker("Add a photo", selection: $selectedItem, matching: .images, photoLibrary: .shared())
// Some lines of code for the PhotosPicker
}
}
// FormViewBis.swift
import SwiftUI
struct FormViewBis: View {
var body: some View {
// The basic elements without the add/save photos feature
}
}
你们会怎么做?谢谢!