Creating a circle button with shadow effect programmatically
As we create our application in Swift, it is vital to to have great design to our UI. One of the easiest way to achieve an appealing design is to add some shadows to texts or buttons. For those who use story board in Swift, you might already know how to add shadows to buttons, but for those who likes to code everything in their application, I want to show you how to add shadow effects programmatically.
Here is a default button that I’ve added in story board. This button looks very plain to me. In order to add some flare to this button, one of my favorite thing to implement is to add shadows and create a circular border. How can we achieve this? Let’s look at some code.
pressButton.layer.shadowColor = UIColor.black.cgColorpressButton.layer.shadowOffset = CGSize(width: 0.0, height: 5.0)pressButton.layer.masksToBounds = falsepressButton.layer.shadowRadius = 2.0pressButton.layer.shadowOpacity = 0.5pressButton.layer.cornerRadius = pressButton.frame.width / 2pressButton.layer.borderColor = UIColor.black.cgColorpressButton.layer.borderWidth = 2.0
Let’s explain what each layer settings does.
- shadowColor = set the shadow’s color
- shadowOffset = sets how far away from the view the shadow should be, to give a 3D offset effect
- masksToBounds = determines if any sublayers of the layer that extend outside its boundaries will be clipped to those boundaries (In my example I have set it to false in order to show my corner radius and shadow effects)
- shadowRadius = sets how wide the shadow should be
- shadowOpacity = sets how transparent the shadow is, where 0 is invisible and 1 is as strong as possible
- cornerRadius = sets the radius of corner (Here I have set it to my button’s frame’s width divided by 2 in order to achieve a circular button. An important thing to note is this will only work if the width and height of the button is equal)
- borderColor = sets color of the border
- borderWidth = sets the width of the border (Without this setting, the border will not render)
Here is the result! It already looks better with a few tweak to the layer settings of the button. There is a wide range of effects that you can achieve by using these settings. I suggest you to play around with each shadow settings to see what you can achieve. That is all for today!
Thanks for tuning in! 😎