Interactive SVG images in Swift with Macaw
How to render SVG images in iOS and handle taps.
Sometimes we need to give the user the opportunity to interact with images on the screen which have several areas (paths) defined, such as SVG Images. The main idea is to have an image where we can interact with each component. For example we can create a map of a country with certain areas so when we tap on a specific one we show certain information to the user.
Rendering an SVG image
In iOS we can achieve this by using Macaw, a pod that provides SVG image rendering and touch handling.
The first thing we need to do is to get well formed SVG image with defined paths and each path should contain an ID (If this is not present, we won’t be able to add touch handling per area).
As an example, a map of Argentina as an SVG file is included below :
After including it in our Xcode project, we can start coding.
In our Storyboard, we have to add an UIView and set it’s class to SVGView from Macaw . After that we can set the SVG image name to render on that view directly from the view property File Name in the attributes inspector for the SVGView . Now if we compile and run, we must see the SVG image in our app.
We must also add a reference to the SVGView outlet in our ViewController.
Displaying the map
If we compile and run, the map is shown.
If we try to tap on any of the provinces, nothing happens.
Touch handling
In order to add a touch handler for a specific path defined in the SVG Image we must add the following lines of code.
If we want to color Buenos Aires province, we must set the nodeTag to AR-B (which is the path ID that matches Buenos Aires province inside our SVG file).
Therefore, we can register for touch events occurring in that particular node inside the SVG Image. As we can see, we call changeNodeColor every time the user taps on that particular node.
The main idea is to get the shape of that particular node and change the fill color, in this case we turn it red: