Impressia/Vernissage/Widgets/ImagesCarousel.swift

69 lines
2.4 KiB
Swift
Raw Normal View History

2023-01-03 14:09:22 +01:00
//
// https://mczachurski.dev
// Copyright © 2023 Marcin Czachurski and the repository contributors.
// Licensed under the MIT License.
//
import SwiftUI
struct ImagesCarousel: View {
2023-01-10 20:38:02 +01:00
@State public var attachments: [AttachmentViewModel]
2023-01-03 14:09:22 +01:00
@State private var height: Double = 0.0
2023-01-14 08:52:51 +01:00
@State private var selectedAttachmentId = String.empty()
2023-01-08 14:50:37 +01:00
2023-01-08 15:43:55 +01:00
@Binding public var exifCamera: String?
@Binding public var exifExposure: String?
@Binding public var exifCreatedDate: String?
@Binding public var exifLens: String?
2023-01-08 14:50:37 +01:00
2023-01-03 14:09:22 +01:00
var body: some View {
2023-01-08 15:43:55 +01:00
TabView() {
2023-01-08 14:50:37 +01:00
ForEach(attachments, id: \.id) { attachment in
2023-01-10 20:38:02 +01:00
if let data = attachment.data, let image = UIImage(data: data) {
2023-01-03 14:09:22 +01:00
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
2023-01-08 14:50:37 +01:00
.tag(attachment.id)
2023-01-03 14:09:22 +01:00
}
}
}
.frame(height: CGFloat(self.height))
.tabViewStyle(PageTabViewStyle())
2023-01-08 14:50:37 +01:00
.onChange(of: selectedAttachmentId, perform: { index in
if let attachment = attachments.first(where: { item in item.id == index }) {
2023-01-08 15:43:55 +01:00
self.exifCamera = attachment.exifCamera
self.exifExposure = attachment.exifExposure
self.exifCreatedDate = attachment.exifCreatedDate
self.exifLens = attachment.exifLens
2023-01-08 14:50:37 +01:00
}
})
2023-01-03 14:09:22 +01:00
.onAppear {
2023-01-14 08:52:51 +01:00
self.selectedAttachmentId = self.attachments.first?.id ?? String.empty()
2023-01-03 14:09:22 +01:00
self.calculateImageHeight()
}
}
private func calculateImageHeight() {
var imageHeight = 0.0
var imageWidth = 0.0
for item in attachments {
2023-01-10 20:38:02 +01:00
if let data = item.data, let image = UIImage(data: data) {
2023-01-03 14:09:22 +01:00
if image.size.height > imageHeight {
imageHeight = image.size.height
imageWidth = image.size.width
}
}
}
let divider = imageWidth / UIScreen.main.bounds.size.width
self.height = imageHeight / divider
}
}
struct ImagesCarousel_Previews: PreviewProvider {
static var previews: some View {
2023-01-08 15:43:55 +01:00
ImagesCarousel(attachments: [], exifCamera: .constant(""), exifExposure: .constant(""), exifCreatedDate: .constant(""), exifLens: .constant(""))
2023-01-03 14:09:22 +01:00
}
}