ImagePicker.swift 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import SwiftUI
  2. import PhotosUI
  3. import UIKit
  4. /// A helper SwiftUI wrapper for UIImagePickerController to select photos or capture via camera.
  5. struct ImagePicker: UIViewControllerRepresentable {
  6. var sourceType: UIImagePickerController.SourceType = .camera
  7. var onImagePicked: (UIImage) -> Void
  8. @Environment(\.dismiss) private var dismiss
  9. func makeUIViewController(context: Context) -> UIImagePickerController {
  10. let picker = UIImagePickerController()
  11. picker.sourceType = sourceType
  12. picker.delegate = context.coordinator
  13. return picker
  14. }
  15. func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
  16. func makeCoordinator() -> Coordinator {
  17. Coordinator(self)
  18. }
  19. class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  20. let parent: ImagePicker
  21. init(_ parent: ImagePicker) {
  22. self.parent = parent
  23. }
  24. func imagePickerController(
  25. _ picker: UIImagePickerController,
  26. didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
  27. ) {
  28. if let image = info[.originalImage] as? UIImage {
  29. parent.onImagePicked(image)
  30. }
  31. parent.dismiss()
  32. }
  33. func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
  34. parent.dismiss()
  35. }
  36. }
  37. }
  38. struct PhotoRecordDraft: Identifiable {
  39. let id: UUID
  40. let image: UIImage
  41. var note: String
  42. init(
  43. id: UUID = UUID(),
  44. image: UIImage,
  45. note: String = ""
  46. ) {
  47. self.id = id
  48. self.image = image
  49. self.note = note
  50. }
  51. }
  52. struct PhotoRecordEditorSheet: View {
  53. @Environment(\.dismiss) private var dismiss
  54. let timeLabel: String
  55. let onSave: ([PhotoRecordDraft], TimelineLocation?) -> Bool
  56. @State private var drafts: [PhotoRecordDraft] = []
  57. @State private var recordLocation: TimelineLocation?
  58. @State private var selectedLibraryItems: [PhotosPickerItem] = []
  59. @State private var showCamera = false
  60. @State private var isLoadingLibrary = false
  61. @State private var loadError: String?
  62. var body: some View {
  63. NavigationStack {
  64. ZStack {
  65. Color.spaceBlack.ignoresSafeArea()
  66. ScrollView {
  67. VStack(alignment: .leading, spacing: 16) {
  68. Label("记录点 \(timeLabel)", systemImage: "clock")
  69. .font(.system(size: 12, weight: .medium, design: .monospaced))
  70. .foregroundStyle(Color.secondary)
  71. HStack(spacing: 12) {
  72. if UIImagePickerController.isSourceTypeAvailable(.camera) {
  73. Button {
  74. showCamera = true
  75. } label: {
  76. photoSourceButtonLabel(
  77. title: "拍照",
  78. systemImage: "camera"
  79. )
  80. }
  81. .buttonStyle(.plain)
  82. }
  83. PhotosPicker(
  84. selection: $selectedLibraryItems,
  85. maxSelectionCount: 0,
  86. matching: .images
  87. ) {
  88. photoSourceButtonLabel(
  89. title: "从相册选择",
  90. systemImage: "photo.on.rectangle"
  91. )
  92. }
  93. .buttonStyle(.plain)
  94. }
  95. TimelineLocationButton(location: $recordLocation)
  96. if isLoadingLibrary {
  97. HStack(spacing: 8) {
  98. ProgressView()
  99. Text("正在读取照片…")
  100. .font(.system(size: 12))
  101. .foregroundStyle(Color.secondary)
  102. }
  103. }
  104. if drafts.isEmpty, !isLoadingLibrary {
  105. ContentUnavailableView(
  106. "还没有照片",
  107. systemImage: "photo.badge.plus",
  108. description: Text("可以连续拍照,也可以从相册一次选择多张。")
  109. )
  110. .frame(maxWidth: .infinity, minHeight: 220)
  111. } else {
  112. LazyVStack(spacing: 14) {
  113. ForEach($drafts) { $draft in
  114. photoDraftCard(draft: $draft)
  115. }
  116. }
  117. }
  118. }
  119. .padding(20)
  120. }
  121. }
  122. .navigationTitle("添加照片记录")
  123. .navigationBarTitleDisplayMode(.inline)
  124. .toolbar {
  125. ToolbarItem(placement: .cancellationAction) {
  126. Button("取消") {
  127. dismiss()
  128. }
  129. }
  130. ToolbarItem(placement: .confirmationAction) {
  131. Button("保存 \(drafts.count) 张") {
  132. if onSave(drafts, recordLocation) {
  133. dismiss()
  134. }
  135. }
  136. .disabled(drafts.isEmpty || isLoadingLibrary)
  137. }
  138. }
  139. }
  140. .fullScreenCover(isPresented: $showCamera) {
  141. ImagePicker(sourceType: .camera) { image in
  142. drafts.append(PhotoRecordDraft(image: image))
  143. }
  144. }
  145. .onChange(of: selectedLibraryItems) { _, newItems in
  146. guard !newItems.isEmpty else { return }
  147. Task {
  148. await importLibraryItems(newItems)
  149. }
  150. }
  151. .alert("无法读取照片", isPresented: Binding(
  152. get: { loadError != nil },
  153. set: { if !$0 { loadError = nil } }
  154. )) {
  155. Button("知道了", role: .cancel) {}
  156. } message: {
  157. Text(loadError ?? "请重新选择照片。")
  158. }
  159. .presentationDetents([.large])
  160. .presentationDragIndicator(.visible)
  161. .presentationBackground(Color.spaceBlack)
  162. }
  163. private func photoSourceButtonLabel(
  164. title: String,
  165. systemImage: String
  166. ) -> some View {
  167. Label(title, systemImage: systemImage)
  168. .font(.system(size: 13, weight: .medium))
  169. .foregroundStyle(Color.primary)
  170. .frame(maxWidth: .infinity)
  171. .padding(.vertical, 12)
  172. .background(Color.cardBackground.opacity(0.35))
  173. .businessBorder(cornerRadius: 8)
  174. .contentShape(Rectangle())
  175. }
  176. private func photoDraftCard(
  177. draft: Binding<PhotoRecordDraft>
  178. ) -> some View {
  179. VStack(alignment: .leading, spacing: 10) {
  180. ZStack(alignment: .topTrailing) {
  181. Image(uiImage: draft.wrappedValue.image)
  182. .resizable()
  183. .scaledToFit()
  184. .frame(maxWidth: .infinity, minHeight: 160, maxHeight: 300)
  185. .clipShape(RoundedRectangle(cornerRadius: 8))
  186. Button(role: .destructive) {
  187. let draftID = draft.wrappedValue.id
  188. drafts.removeAll { $0.id == draftID }
  189. } label: {
  190. Image(systemName: "trash")
  191. .font(.system(size: 12, weight: .semibold))
  192. .foregroundStyle(.white)
  193. .frame(width: 32, height: 32)
  194. .background(.black.opacity(0.6), in: Circle())
  195. }
  196. .padding(8)
  197. .accessibilityLabel("移除这张照片")
  198. }
  199. ZStack(alignment: .topLeading) {
  200. if draft.wrappedValue.note.isEmpty {
  201. Text("照片备注")
  202. .font(.system(size: 14))
  203. .foregroundStyle(Color.secondary.opacity(0.55))
  204. .padding(.horizontal, 15)
  205. .padding(.vertical, 17)
  206. .allowsHitTesting(false)
  207. }
  208. TextEditor(text: draft.note)
  209. .font(.system(size: 14))
  210. .foregroundStyle(Color.primary)
  211. .scrollContentBackground(.hidden)
  212. .padding(8)
  213. .frame(height: 72)
  214. }
  215. .background(Color.cardBackground.opacity(0.45))
  216. .businessBorder(cornerRadius: 8)
  217. }
  218. .padding(12)
  219. .background(Color.cardBackground.opacity(0.18))
  220. .businessBorder(cornerRadius: 10)
  221. }
  222. @MainActor
  223. private func importLibraryItems(_ items: [PhotosPickerItem]) async {
  224. isLoadingLibrary = true
  225. defer {
  226. isLoadingLibrary = false
  227. selectedLibraryItems = []
  228. }
  229. var importedDrafts: [PhotoRecordDraft] = []
  230. var failedCount = 0
  231. for item in items {
  232. do {
  233. guard let data = try await item.loadTransferable(type: Data.self),
  234. let image = UIImage(data: data) else {
  235. failedCount += 1
  236. continue
  237. }
  238. importedDrafts.append(PhotoRecordDraft(image: image))
  239. } catch {
  240. failedCount += 1
  241. }
  242. }
  243. drafts.append(contentsOf: importedDrafts)
  244. if failedCount > 0 {
  245. loadError = failedCount == items.count
  246. ? "所选照片均无法读取,请重新选择。"
  247. : "有 \(failedCount) 张照片无法读取,其余照片已添加。"
  248. }
  249. }
  250. }