HidetoshiYanagisawa
Posted on August 22, 2023
When developing apps with SwiftUI, you might encounter the need to handle SVGs. Since SwiftUI does not natively support SVGs, in this article, we will explore how to display SVGs using the third-party library SwiftSVG.
Table of Contents
Introducing SwiftSVG
To add SwiftSVG to your project, you can easily integrate it using the Swift Package Manager.
- Open Xcode and select your desired project.
- Navigate to
File
>Swift Packages
>Add Package Dependency...
. - Enter the package repository URL as
https://github.com/mchoe/SwiftSVG.git
and click "Next". - Choose the version you need and click "Next".
- Select the target you wish to install to and click "Finish".
import SwiftSVG
Adding SVG Files to Your Project
Adding SVG files to your Xcode project is straightforward.
- Open the Xcode project navigator.
- Drag and drop the SVG file directly from Finder.
- Ensure the following options are selected:
- Copy items if needed
- Create groups
- Add to targets (select the main app target)
Displaying SVG in SwiftUI
Below is a basic way to display SVGs in SwiftUI using SwiftSVG:
import SwiftSVG
let svgView = UIView(SVGNamed: "your_svg_name") { (svgLayer) in
svgLayer.resizeToFit(self.bounds)
}
struct SVGView: UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
return svgView
}
func updateUIView(_ uiView: UIView, context: Context) {
}
}
Now, you can use the SVGView
within your SwiftUI view hierarchy to display the SVG.
Conclusion
In this article, we delved into how to handle SVG files in SwiftUI using the SwiftSVG library. With SwiftSVG, displaying SVGs in your SwiftUI app becomes a breeze. If you have requirements around SVGs, consider introducing this library to your toolkit.
Your feedback and likes are much appreciated!
Posted on August 22, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.