Categories: Swift Programming

Circular UIView with Slider

Sometimes you might want to create a Circle out of a UIView or want to create an static Circle on the view or subview or on a map which always stays at the center because there is no way you can keep the provided Circle class (Google Maps) of a map always at the center.

Let’s see how to do that.

Create a new project and drag a Slider on the controller, create it’s action of type UISlider and set its Minimum and Maximum value to 30 and 200 respectively(or whatever you like).

Create two variables

let circleView = UIView()
var sliderCurrentValue : CGFloat!

and write the following function in your ViewController.

func circularView(x : CGFloat, y : CGFloat , radius : CGFloat ){
circleView.frame = CGRectMake(x, y , radius, radius)
self.circleView.layer.borderColor = UIColor(red: 247.0/255, green: 159.0/255, blue: 50.0/255, alpha: 1.0).CGColor
self.circleView.layer.borderWidth = 3;
circleView.backgroundColor = UIColor(red: 158.0/255, green: 220.0/255, blue: 247.0/255, alpha: 0.5)

view.addSubview(circleView)
view.bringSubviewToFront(circleView)

self.circleView.layer.cornerRadius = CGRectGetWidth(self.circleView.frame)/2
self.circleView.clipsToBounds = true
circleView.userInteractionEnabled = false;
}

After that in your viewDidLoad() call your function.

override func viewDidLoad() {
super.viewDidLoad()
circularView(view.center.x - 30/2, y: view.center.y - 30/2, radius: 30)
}

After that in your Slider Action

 

@IBAction func sliderAction(sender: UISlider) {
sliderCurrentValue = CGFloat(sender.value)
circularView(view.center.x - sliderCurrentValue/2, y: view.center.y - sliderCurrentValue/2, radius: sliderCurrentValue)

}

The circle grows in x and y dimensions downwards when the slider is increased. The only reason half of the current value of the slider was subtracted from the center of both x and y was to make the circle grow in size from the center.

At last run and test your code, following result will be achieved.

Download its source from Github.
Cheers!

Aaqib Hussain

View Comments

Recent Posts

Things to know when moving to Germany

This article covers some important things you must know when you are considering a move…

3 years ago

Unit Testing in Android for Dummies

What is Unit Testing? In its simplest term, unit testing is testing a small piece…

4 years ago

Factory Design Pattern

In this article, you will learn about a type of Creational Design Pattern which is…

5 years ago

Creating Target specific Theme in iOS

In this tutorial, you will go through the use of targets to achieve two separate…

5 years ago

Facade Design Pattern

In this article, you will learn about a type of Structural Design Pattern which is…

5 years ago

Singleton Design Pattern

In this article you will learn about a type of Creational Design Pattern which is…

5 years ago