//
// PhotoPickerBootcamp.swift
// SwiftUIStudy
//
// Created by 김재원 on 4/11/24.
//
import PhotosUI
import SwiftUI
@MainActor
final class PhotoPickerViewModel: ObservableObject {
@Published private(set) var selectedImage: UIImage? = nil
@Published var imageSelection: PhotosPickerItem? = nil {
didSet {
setImage(from: imageSelection)
}
}
@Published private(set) var selectedImages: [UIImage] = []
@Published var imageSelections: [PhotosPickerItem] = [] {
didSet {
setImages(from: imageSelections)
}
}
private func setImage(from selection: PhotosPickerItem?) {
guard let selection else { return }
Task {
if let data = try? await selection.loadTransferable(type: Data.self) {
if let uiimage = UIImage(data: data) {
selectedImage = uiimage
return
}
}
}
}
private func setImages(from selections: [PhotosPickerItem]) {
Task {
var uiimages: [UIImage] = []
for selection in selections {
if let data = try? await selection.loadTransferable(type: Data.self) {
if let uiimage = UIImage(data: data) {
uiimages.append(uiimage)
}
}
}
selectedImages = uiimages
}
}
}
struct PhotoPickerBootcamp: View {
@StateObject private var viewModel = PhotoPickerViewModel()
var body: some View {
VStack(spacing: 40) {
Text("Photo Picker bootcamp")
if let image = viewModel.selectedImage {
Image(uiImage: image)
.resizable()
.scaledToFill()
.frame(width: 200, height: 200)
.cornerRadius(10)
}
PhotosPicker(selection: $viewModel.imageSelection) {
Text("Open the photo picker!")
.foregroundColor(.red)
}
if !viewModel.imageSelections.isEmpty {
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(viewModel.selectedImages, id: \.self) { image in
Image(uiImage: image)
.resizable()
.scaledToFill()
.frame(width: 50, height: 50)
.cornerRadius(10)
}
}
}
}
PhotosPicker(selection: $viewModel.imageSelections) {
Text("Open the photo picker!")
.foregroundColor(.red)
}
}
}
}
#Preview {
PhotoPickerBootcamp()
}
반응형
'프로그래밍' 카테고리의 다른 글
"git push -u origin main" 명령어 (0) | 2024.12.12 |
---|---|
Flexbox와 Grid에서 justify-content와 align-items 속성 사용법 (0) | 2024.12.05 |
"Sign Up"과 "Sign In" 차이 (0) | 2024.01.08 |
[Flutter] 애니메이션 효과 만들기 - AnimationBuilder 위젯 (0) | 2024.01.05 |
[CSS] 반응형 웹디자인 기본: 미디어쿼리 & 뷰포트 (0) | 2024.01.03 |