SwiftUI: Difference between revisions

From Chorke Wiki
Jump to navigation Jump to search
Line 23: Line 23:
     static var previews: some View {
     static var previews: some View {
         ContentView()
         ContentView()
    }
}
</source>
==MyPDFView==
<source lang="swift">
// MARK: - MyPDFView
fileprivate struct MyPDFView: UIViewRepresentable {
    @Binding var data: Data
    func makeUIView(context: UIViewRepresentableContext<MyPDFView>) -> UIView {
        let empty = UIView()
        guard let provider = CGDataProvider(data: self.data as CFData) else {return empty}
        guard let document = CGPDFDocument(provider) else {return empty}
        guard let page    = document.page(at: 1) else {return empty}
        let pageRect = page.getBoxRect(.mediaBox)
        let renderer = UIGraphicsImageRenderer(size: pageRect.size)
        let uiImage  = renderer.image { ctx in
            UIColor.white.set()
            ctx.fill(pageRect)
            ctx.cgContext.translateBy(x: 0.0, y: pageRect.size.height)
            ctx.cgContext.scaleBy(x: 1.0, y: -1.0)
            ctx.cgContext.drawPDFPage(page)
        }
        return UIImageView(image: uiImage)
    }
    func updateUIView(_ view: UIView, context: UIViewRepresentableContext<MyPDFView>) {
        // MARK: - TODO
     }
     }
}
}

Revision as of 07:08, 11 April 2020

ContentView

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Turtle Rock")
                .font(.title)
            HStack {
                Text("Joshua Tree National Park")
                    .font(.subheadline)
                Spacer()
                Text("California")
                    .font(.subheadline)
            }
        }
        .padding()
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

MyPDFView

// MARK: - MyPDFView
fileprivate struct MyPDFView: UIViewRepresentable {
    @Binding var data: Data

    func makeUIView(context: UIViewRepresentableContext<MyPDFView>) -> UIView {
        let empty = UIView()
        guard let provider = CGDataProvider(data: self.data as CFData) else {return empty}
        guard let document = CGPDFDocument(provider) else {return empty}
        guard let page     = document.page(at: 1) else {return empty}
        let pageRect = page.getBoxRect(.mediaBox)
        let renderer = UIGraphicsImageRenderer(size: pageRect.size)
        let uiImage  = renderer.image { ctx in
            UIColor.white.set()
            ctx.fill(pageRect)
            ctx.cgContext.translateBy(x: 0.0, y: pageRect.size.height)
            ctx.cgContext.scaleBy(x: 1.0, y: -1.0)
            ctx.cgContext.drawPDFPage(page)
        }
        return UIImageView(image: uiImage)
    }

    func updateUIView(_ view: UIView, context: UIViewRepresentableContext<MyPDFView>) {
        // MARK: - TODO
    }
}

References