2021-06-15 2 分钟 0.2 k0次访问
swiftui 通过tabview实现图片查看器
效果图
- 核心思路为通过tabview包裹图片 然后设置样式.tabViewStyle(PageTabViewStyle()).indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
- 通过ZoomableScrollView组件实现图片的缩放,效果可以说是相当完美了
- 感谢 jtbandes 真的是救我狗命
核心代码1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| struct ImageTabView: View { @EnvironmentObject var imageTabViewEnviroment:ImageTabViewEnvironment
var body: some View { VStack{ TabView(selection:$imageTabViewEnviroment.index) { ForEach(0..<imageTabViewEnviroment.imageArray.count,id: \.self){ index in ImageTabViewItemView(imageUrl: imageTabViewEnviroment.imageArray[index]) } } .tabViewStyle(PageTabViewStyle()) .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always)) } .edgesIgnoringSafeArea(.all) } }
private struct ImageTabViewItemView:View { @State var scale: CGFloat = 1 @State private var dragOffset = CGSize.zero @State var imageUrl: String var body: some View{ VStack{ ZoomableScrollView { MyKingfisherView(urlStr: imageUrl) } } .frame(height:UIScreen.main.bounds.height) .clipped() } }
struct ZoomableScrollView<Content: View>: UIViewRepresentable { private var content: Content
init(@ViewBuilder content: () -> Content) { self.content = content() }
func makeUIView(context: Context) -> UIScrollView { // set up the UIScrollView let scrollView = UIScrollView() scrollView.delegate = context.coordinator // for viewForZooming(in:) scrollView.maximumZoomScale = 20 scrollView.minimumZoomScale = 1 scrollView.bouncesZoom = true
// create a UIHostingController to hold our SwiftUI content let hostedView = context.coordinator.hostingController.view! hostedView.translatesAutoresizingMaskIntoConstraints = true hostedView.autoresizingMask = [.flexibleWidth, .flexibleHeight] hostedView.frame = scrollView.bounds scrollView.addSubview(hostedView)
return scrollView }
func makeCoordinator() -> Coordinator { return Coordinator(hostingController: UIHostingController(rootView: self.content)) }
func updateUIView(_ uiView: UIScrollView, context: Context) { // update the hosting controller's SwiftUI content context.coordinator.hostingController.rootView = self.content assert(context.coordinator.hostingController.view.superview == uiView) }
// MARK: - Coordinator
class Coordinator: NSObject, UIScrollViewDelegate { var hostingController: UIHostingController<Content>
init(hostingController: UIHostingController<Content>) { self.hostingController = hostingController }
func viewForZooming(in scrollView: UIScrollView) -> UIView? { return hostingController.view } } }
|