04
Nov
2020
SVG images in SwiftUI
Reading time: 1 min
This tutorial shows how to use SVG images in SwiftUI.
First, add the Macaw library to your project. Then, wrap its SVGView
using this simple UIViewRepresentable
wrapper:
import Macaw
struct SVGImage: UIViewRepresentable {
// a binding allows for dynamic updates to the shown image
@Binding var name: String
init(name: Binding<String>) {
_name = name
}
// convenience constructor to allow for a constant image name
init(name: String) {
_name = .constant(name)
}
func makeUIView(context: Context) -> SVGView {
let svgView = SVGView()
svgView.backgroundColor = UIColor(white: 1.0, alpha: 0.0) // otherwise the background is black
svgView.contentMode = .scaleToFill
return svgView
}
func updateUIView(_ uiView: SVGView, context: Context) {
uiView.fileName = name
}
}
Then, just add your SVG files to the Resources folder, and you're good to go!
When using SVGImage
, make sure to pass a frame
to it:
struct MyView: View {
@Binding var image2Name = "image2"
var body: some View {
VStack {
SVGImage(name: "image1")
.frame(width: 50, height: 50)
Button(action: {
image2Name = "image3"
}) {
SVGImage(name: $image2Name)
.frame(width: 60, height: 40)
}
}
}
}