Created
April 23, 2024 07:47
-
-
Save karm435/a6bf4d9f48e05dc7ca7e649328544dba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import UIKit | |
import TOCropViewController | |
struct Page: Identifiable { | |
var id: Int | |
var image: Image | |
} | |
struct ContentView: View { | |
var samplePages: [Page] = [ | |
.init(id: 1, image: Image(systemName: "rectangle.portrait.and.arrow.right")), | |
.init(id: 2, image: Image(systemName: "square.and.pencil")), | |
.init(id: 3, image: Image(systemName: "square.and.pencil.circle.fill")), | |
.init(id: 4, image: Image(systemName: "scribble")), | |
.init(id: 5, image: Image(systemName: "square.and.arrow.up.circle.fill")), | |
] | |
var body: some View { | |
VStack { | |
HorizontalImageScrollView(pages: samplePages) | |
} | |
.padding() | |
} | |
} | |
#Preview { | |
ContentView() | |
} | |
struct HorizontalImageScrollView: View { | |
let pages: [Page] | |
@State private var isShowingCropViewController = false | |
@State private var indexForVisibleImage: Int? = 1 | |
var body: some View { | |
NavigationStack { | |
VStack { | |
ScrollView(.horizontal, showsIndicators: true) { | |
HStack(spacing: 10) { | |
ForEach(pages, id: \.id) { page in | |
page.image | |
.resizable() | |
.aspectRatio(contentMode: .fit) | |
.containerRelativeFrame(.horizontal) | |
} | |
}.scrollTargetLayout() | |
} | |
.contentMargins(16, for: .scrollContent) | |
.scrollTargetBehavior(.viewAligned) | |
.scrollPosition(id: $indexForVisibleImage) | |
.padding(.bottom, 20) | |
Text("current Index \(indexForVisibleImage ?? 1)") | |
} | |
.navigationBarTitleDisplayMode(.inline) | |
.navigationTitle("Preview") | |
.toolbar { | |
ToolbarItem(placement: .topBarTrailing) { | |
Button(action: { | |
self.isShowingCropViewController.toggle() | |
}) { | |
Text("Edit") | |
} | |
} | |
}.sheet(isPresented: $isShowingCropViewController) { | |
if let index = indexForVisibleImage { | |
self.pages[index].image | |
.resizable() | |
.scaledToFit() | |
} | |
} | |
} | |
} | |
} | |
struct CropViewControllerWrapper: UIViewControllerRepresentable { | |
let image: Image | |
func makeUIViewController(context: Context) -> some UIViewController { | |
let cropViewController = TOCropViewController(image: image.convertToUIImage()!) | |
cropViewController.toolbarPosition = .top | |
return cropViewController | |
} | |
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { | |
// Update the view controller if needed | |
} | |
} | |
extension Image { | |
@MainActor func convertToUIImage() -> UIImage? { | |
return ImageRenderer(content: self).uiImage | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment