This guide covers a simple way to use SVG (Scalable Vector Graphics) assets in your iOS app. This was tested on macOS High Sierra 10.13 with Xcode 9.4 and Swift 4.
There are many websites where you can find SVG icons. Check out Material or ionicons
- Install homebrew & python3 for macOS (if you don’t have it)
- Install cairosvg. The code below installs various dependencies
brew install python3 cairo pango gdk-pixbuf libffi pip3 install cairosvg
- Convert your SVG icons to PDF files. Make sure to navigate to the location of your SVG icon files. Run this command for each icon file (with the relevant *.svg & *.pdf input / output file name):
cairosvg icon.svg -o icon.pdf
- Drag your PDF files into your Xcode Assets.xcassets folder
- Adjust the settings for each icon in your xcassets. You may want to adjust:
- Name – this is important as you will refer to this in your Swift code to use the icon
- Set ‘Render As’ to ‘Template Image’
- Check the box for ‘Resizing – Preserve Vector Data’
- Set ‘Scales’ to ‘Single Scale’
- Use your icon in your app. I did this programmatically in Swift, and this works in your ViewController. Make sure to update the ‘iconName’ to match what is in your xcassets for your icon file.
if let icon = UIImage(named: "iconName") { let image = UIImageView(image: icon) image.translatesAutoresizingMaskIntoConstraints = false image.tintColor = UIColor.blue view.addSubview(image) NSLayoutConstraint.activate([ image.leadingAnchor.constraint(equalTo: view.leadingAnchor), image.centerYAnchor.constraint(equalTo: view.centerYAnchor), image.widthAnchor.constraint(equalToConstant: 24), image.heightAnchor.constraint(equalToConstant: 24), ]) }
- That’s it. Your SVG file was converted to a PDF file, added into your Xcode assets, and called from your ViewController!