Today we will learn How to create custom UIView Shapes in iOS Swift 2.1. As sometimes we need to create custom shapes according to App’s requirement.
We will start by creating a new project and Choosing language Swift, i’m using Xcode 7.2 version.
So create New project name it CustomShapes and save it.
Now in Main.storyboard drag drop a UIView on controller and change its Background Color to Blue.
After then add Constraints to your view.
As we are creating custom view so we will create a new sub class of UIView. Name is “Shape”. Add new file > cocoa touch class > sub class of UIView name Shape. Then save it.
We will only override the “drawRect” method as it is also written in the newly build sub class of UIView.
Let Start customising view.
First we create a layer and then we will customise it accordingly .
let mask = CAShapeLayer()
mask.frame = self.layer.bounds
let width = self.layer.frame.size.width
let height = self.layer.frame.size.height
After that we will create a path its like out lining the shape of the view and later applying it on view.
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 0, 70)
CGPathAddLineToPoint(path, nil, width, 0)
CGPathAddLineToPoint(path, nil, width, height-70)
CGPathAddLineToPoint(path, nil, 0, height)
CGPathAddLineToPoint(path, nil, 0, 70)
mask.path = path
After that we will apply that path on the view.
self.layer.mask = mask
let shape = CAShapeLayer()
shape.frame = self.bounds
shape.path = path
shape.lineWidth = 0
shape.strokeColor = UIColor.whiteColor().CGColor
shape.fillColor = UIColor.clearColor().CGColor
self.layer.insertSublayer(shape, atIndex: 0)
That all the coding part we have to do in this class now run the programme.
There will be a blue rectangle on the screen we forgot one thing to select the view and change its class to “Shape”.
Now again run the project you will see the shape we just created.
You finally create your own custom view, you can change your shape.
Another news for you all now you can download the full project. You can download this project from here.
Today we learn How to create custom UIView Shapes in iOS Swift 2.1. Next time we will do some more animations till then Happy Coding 🙂