Skip to content

Instantly share code, notes, and snippets.

@takoikatakotako
Created October 28, 2024 15:56
Show Gist options
  • Select an option

  • Save takoikatakotako/8de43b2f18e1f5bc893e34d2e6d0b245 to your computer and use it in GitHub Desktop.

Select an option

Save takoikatakotako/8de43b2f18e1f5bc893e34d2e6d0b245 to your computer and use it in GitHub Desktop.
SwiftUIでカメラを使う
import SwiftUI
public struct CameraView: UIViewControllerRepresentable {
@Environment(\.dismiss) private var dismiss
@Binding var images: [UIImage]
public func makeCoordinator() -> Coordinator {
Coordinator(self)
}
public func makeUIViewController(context: Context) -> UIImagePickerController {
let viewController = UIImagePickerController()
viewController.delegate = context.coordinator
if UIImagePickerController.isSourceTypeAvailable(.camera) {
viewController.sourceType = .camera
}
return viewController
}
public func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
}
extension CameraView {
public class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let parent: CameraView
init(_ parent: CameraView) {
self.parent = parent
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let uiImage = info[.originalImage] as? UIImage {
self.parent.images.append(uiImage)
}
self.parent.dismiss()
}
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.parent.dismiss()
}
}
}
import SwiftUI
struct ContentView: View {
@State var images: [UIImage] = []
@State var showingSheet = false
var body: some View {
VStack {
ScrollView(.horizontal) {
HStack {
ForEach(0..<images.count, id: \.self) { index in
Image(uiImage: images[index])
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 160)
.clipped()
}
}
}
Button {
showingSheet = true
} label: {
Text("Take Photo!")
}
}
.sheet(isPresented: $showingSheet) {
CameraView(images: $images)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment