2

My source code is very simple as follow:

//
//  SVGImage.swift
//  WorldRoad
//
//  Created by norains on 2019/11/26.
//  Copyright © 2019 norains. All rights reserved.
//

import PocketSVG
import SwiftUI

struct SVGImage: UIViewRepresentable {

    func makeUIView(context: Context) -> SVGImageView {
        let url = Bundle.main.url(forResource: "tiger", withExtension: "svg")!
        let svgImageView = SVGImageView.init(contentsOf: url)
        //svgImageView.frame = view.bounds //Could not set the frame here
        svgImageView.contentMode = .scaleAspectFit
        
        return svgImageView
    }

    func updateUIView(_ view: SVGImageView, context: Context) {
        
    }
}

struct SVGImage_Previews: PreviewProvider {
    static var previews: some View {
        return SVGImage()
    }
}

But it display just like that: enter image description here

It looks like the view is bigger than the screen.

The normal should like this: enter image description here

How could I do ? Thank you!

Community
  • 1
  • 1
norains
  • 743
  • 1
  • 5
  • 12

1 Answers1

2

It will work if you embed the SVGImageView inside a UIView like the following:

import PocketSVG
import SwiftUI

struct SVGImage: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        let svgView = UIView(frame: UIScreen.main.bounds)
        let url = Bundle.main.url(forResource: "tiger", withExtension: "svg")!
        let svgImageView = SVGImageView.init(contentsOf: url)
        svgImageView.frame = svgView.bounds
        svgImageView.contentMode = .scaleAspectFit
        svgView.addSubview(svgImageView)

        return svgView
    }

    func updateUIView(_ view: UIView, context: Context) {

    }
}

struct SVGImage_Previews: PreviewProvider {
    static var previews: some View {
        return SVGImage()
    }
}
gotnull
  • 26,454
  • 22
  • 137
  • 203