How to create a circular button in Swift?

IosSwiftUibutton

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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")
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUserView Question on Stackoverflow
Solution 1 - IosvacawamaView Answer on Stackoverflow