티스토리 뷰
사진 추가하기 시도해봄
1. ImagePicker.swift
import SwiftUI
import PhotosUI
@MainActor
class ImagePicker: ObservableObject {
@Published var image: Image?
@Published var images: [Image] = []
@Published var imageSelection: PhotosPickerItem? {
didSet {
if let imageSelection {
Task {
try await loadTransferable(from: imageSelection)
}
}
}
}
@Published var imageSelections: [PhotosPickerItem] = [] {
didSet {
Task {
if !imageSelections.isEmpty {
try await loadTransferable(from: imageSelections)
imageSelections = []
}
}
}
}
func loadTransferable(from imageSelections: [PhotosPickerItem]) async throws {
do {
for imageSelection in imageSelections {
if let data = try await imageSelection.loadTransferable(type: Data.self) {
if let uiImage = UIImage(data: data) {
self.images.append(Image(uiImage: uiImage))
}
}
}
} catch {
print(error.localizedDescription)
}
}
func loadTransferable(from imageSelection: PhotosPickerItem?) async throws {
// print(Image.transferRepresentation)
do {
if let data = try await imageSelection?.loadTransferable(type: Data.self) {
if let uiImage = UIImage(data: data) {
self.image = Image(uiImage: uiImage)
}
}
} catch {
print(error.localizedDescription)
image = nil
}
}
}
2. View에 기능 추가
import SwiftUI
import PhotosUI
struct ImagePickerView: View {
@StateObject var imagePicker = ImagePicker()
... 생략 ...
HStack {
if let image = imagePicker.image {
image
.resizable()
.frame(width: 100, height: 100)
.scaledToFit()
.clipShape(RoundedRectangle(cornerRadius: 8))
}
Button(action: {}) {
PhotosPicker(selection: $imagePicker.imageSelection,
matching: .images,
photoLibrary: .shared()) {
Image(systemName: "plus.circle.fill")
.resizable()
.frame(width: 30, height: 30)
.tint(.primaryRed)
}
}
.frame(width: 100, height: 100)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(Color.navGray)
)
}
... 생략 ...
참고 링크
반응형
LIST
'공부합시다 > Swift' 카테고리의 다른 글
[Swift 문법] 변수 / 상수 / 데이터 타입 / 연산자 (0) | 2023.04.27 |
---|---|
[SwiftUI] image 위에 image 얹기(ZStack) (0) | 2022.12.03 |
[SwiftUI] imagePicker 사용기2 - 사진 추가 무한 스크롤 수정 및 사진 최대 개수 지정(maxSelectionCount) (0) | 2022.11.18 |
[SwiftUI] Local에 저장된 JSON file parse & decode 하기 (0) | 2022.11.03 |
[UIKit] Could not find a storyboard named ... (0) | 2022.10.11 |
댓글