How to create a circular button in Swift?

User picture User · Sep 26, 2014 · Viewed 84.9k times · Source

I want to make a circular thumbs up and thumbs down button.

Should I use a ImageView or a Button as the super class?

How would I do this in Swift?

Answer

vacawama picture vacawama · Sep 26, 2014

Here is an example round button:

Swift 3, 4, 5:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let button = UIButton(type: .custom)
    button.frame = CGRect(x: 160, y: 100, width: 50, height: 50)
    button.layer.cornerRadius = 0.5 * button.bounds.size.width
    button.clipsToBounds = true
    button.setImage(UIImage(named:"thumbsUp.png"), for: .normal)
    button.addTarget(self, action: #selector(thumbsUpButtonPressed), for: .touchUpInside)
    view.addSubview(button)
}

@objc func thumbsUpButtonPressed() {
    print("thumbs up button pressed")
}

Swift 2.x:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let button = UIButton(type: .Custom)
    button.frame = CGRect(x: 160, y: 100, width: 50, height: 50)
    button.layer.cornerRadius = 0.5 * button.bounds.size.width
    button.clipsToBounds = true
    button.setImage(UIImage(named:"thumbsUp.png"), forState: .Normal)
    button.addTarget(self, action: #selector(thumbsUpButtonPressed), forControlEvents: .TouchUpInside)
    view.addSubview(button)
}

func thumbsUpButtonPressed() {
    print("thumbs up button pressed")
}