はじめに
PhotosPickerを使ったことがなかったので次回からスムーズに使えるようにPhotosPicker
の最小単位を記録しておきます。
実装
写真を1枚選択する
import SwiftUI
import PhotosUI
struct SwiftUIView: View {
@State private var selectedPhoto: PhotosPickerItem?
@State private var uiImage: UIImage?
var body: some View {
VStack {
if let uiImage {
Image(uiImage: uiImage)
.resizable()
.scaledToFit()
.padding(20)
}
PhotosPicker("写真を選択", selection: $selectedPhoto)
.onChange(of: selectedPhoto) { selectedPhoto in
Task { await loadImageFromSelectedPhoto(photo: selectedPhoto) }
}
}
}
private func loadImageFromSelectedPhoto(photo: PhotosPickerItem?) async {
if let data = try? await photo?.loadTransferable(type: Data.self) {
self.uiImage = UIImage(data: data)
}
}
}
写真を複数選択する
import SwiftUI
import PhotosUI
struct SwiftUIView: View {
@State private var selectedPhotos: [PhotosPickerItem] = []
@State private var uiImages: [UIImage?] = []
var body: some View {
VStack {
ScrollView(.horizontal) {
HStack {
ForEach(uiImages, id: \.self) { uiImage in
if let uiImage {
Image(uiImage: uiImage)
.resizable()
.scaledToFit()
.padding(20)
}
}
}
}
PhotosPicker("写真を選択", selection: $selectedPhotos)
.onChange(of: selectedPhotos) { selectedPhotos in
Task { await loadImageFromSelectedPhoto(photos: selectedPhotos) }
}
}
}
private func loadImageFromSelectedPhoto(photos: [PhotosPickerItem]) async {
for photo in photos {
if let data = try? await photo.loadTransferable(type: Data.self) {
self.uiImages.append(UIImage(data: data))
}
}
}
}
おわり
めっちゃ簡単に使えて便利ですね