3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

はじめに

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))
            }
        }
    }
}

おわり

めっちゃ簡単に使えて便利ですね

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?