iOS Swift Add SVG Image to button like Android

UPD: Also see this UseYourLoaf blog post

Just found on Erica Sadun blog post that on iOS 11 you could use Vector Assets.

What "Vector Assets" mean:

If you click that box, the vector data will be shipped with your application. Which, on the one hand, makes your application a little bit larger, because the vector data takes up some space. But on the other hand, will give you the opportunity to scale these images, which might be useful in a number of different situations. So, one is, if you know that this particular image is going to be used at multiple sizes. But that might be less obvious. So, one case is a symbolic glyph that should resize with dynamic type. Since we're thinking about dynamic type, you should also be thinking about having glyphs that are appearing next to type resize appropriately. Another case that's really not obvious, is tab bar images. ... there's a really great accessibility feature that we strongly recommend supporting, that allows for user that have turned their dynamic type size up. ... So, we really recommend doing that to increase the usability of your app across all users

How to use:

  1. Convert your SVG file into PDF, e.g. on ZamZar.com
  2. Add your pdf to Assets.xcassets
    • Click "Preserve Vector Data" for the imported pdf.
  3. Create UIImageView in your UIViewController and assign pdf file like UIImage.

or Asset Catalog Creator available in the Mac App Store will do steps 1 and 2 with a simple drag and drop.


iOS < 11

There is no native way to use SVG image.

Take a look at Macaw

Import framework via Cocoapod

pod "Macaw", "0.8.2"

Check their example project: this is how you render tiger.svg (located in project directory, not in an Assets.xcassets file)

import UIKit
import Macaw

class SVGExampleView: MacawView {

    required init?(coder aDecoder: NSCoder) {
        super.init(node: SVGParser.parse(path: "tiger"), coder: aDecoder)
    }

}

There are some other third-party libraries of course:

  • SwiftSVG
  • Snowflake
  • SVGKit Objective-C framework

After a nightmare I came up with this solution for using SVG in button using Swift. This is for all who dont wish to struggle like me

I used the simple SwiftSVG library for getting UIView from SVG File

Usage :

namBtnVar.setSvgImgFnc("ikn_sev", ClrVar: UIColor.cyanColor())

Install SwiftSVG Library

1) Use pod to install :

// For Swift 3

pod 'SwiftSVG'

// For Swift 2.3

pod 'SwiftSVG', '1.1.5'

2) Add framework

Goto AppSettings
-> General Tab
-> Scroll down to Linked Frameworks and Libraries
-> Click on plus icon
-> Select SVG.framework

3) Add below code anywhere in your project

extension UIButton
{
    func setSvgImgFnc(svgImjFileNameVar: String, ClrVar: UIColor)
    {
        setImage((getSvgImgFnc(svgImjFileNameVar, ClrVar : ClrVar)), forState: .Normal)
    }
}

func getSvgImgFnc(svgImjFileNameVar: String, ClrVar: UIColor) -> UIImage
{
    let svgURL = NSBundle.mainBundle().URLForResource(svgImjFileNameVar, withExtension: "svg")
    let svgVyuVar = UIView(SVGURL: svgURL!)

    /* The width, height and viewPort are set to 100 

        <svg xmlns="http://www.w3.org/2000/svg"
            width="100%" height="100%"
            viewBox="0 0 100 100">

        So we need to set UIView Rect also same
    */

    svgVyuVar.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    for svgVyuLyrIdx in svgVyuVar.layer.sublayers!
    {
        for subSvgVyuLyrIdx in svgVyuLyrIdx.sublayers!
        {
            if(subSvgVyuLyrIdx.isKindOfClass(CAShapeLayer))
            {
                let SvgShpLyrIdx = subSvgVyuLyrIdx as? CAShapeLayer
                SvgShpLyrIdx!.fillColor = ClrVar.CGColor
            }
        }
    }
    return svgVyuVar.getImgFromVyuFnc()
}

extension UIView
{
    func getImgFromVyuFnc() -> UIImage
    {
        UIGraphicsBeginImageContext(self.frame.size)

        self.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()
        return image!
    }
}

You can use vector-based PDFs natively if you select Single Scale for Scale Factors after importing.

The dimensions of the PDF will be the 1x dimensions for the asset.

Xcode will generate the rasterized image for every scale. You can then use it like any other image.