sriram hegde
sriram hegde

Reputation: 2471

Making Buttons Circular in swift4

I have few buttons which are added from Storyboard(not by code) . I want to make it circular in shape . How do I do it? I don't want a circular button added from code but from storyboard.Thanks

Upvotes: 2

Views: 6906

Answers (3)

Raghib Arshi
Raghib Arshi

Reputation: 755

Very simple and easy.

yourButton.layer.cornerRadius = yourButton.frame.width/2

this will surely going to work. Eat sleep code repeat😇

Upvotes: 4

technerd
technerd

Reputation: 14504

You can make use of IBDesginable to make UIButton circular even in storyboard.

Add this class RoundButton in your project.

@IBDesignable class RoundButton : UIButton{

    override init(frame: CGRect) {
        super.init(frame: frame)
        sharedInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        sharedInit()
    }

    override func prepareForInterfaceBuilder() {
        sharedInit()
    }

    func sharedInit() {
        refreshCorners(value: cornerRadius)
    }

    func refreshCorners(value: CGFloat) {
        layer.cornerRadius = value
    }

    @IBInspectable var cornerRadius: CGFloat = 15 {
        didSet {
            refreshCorners(value: cornerRadius)
        }
    }
}

Follow below steps to make it designable in Storyboard.

  1. Add UIButton in viewcontroller and set some background color.

enter image description here

  1. Set Width and Height same. Here both are 100.

enter image description here

  1. Now you can see one more property named Corner Radius we declared in RoundButton class. Set it to 50 as half of Width/Height. You can set according to your need.

enter image description here

Now you can see rounded corner button within storyboard. You do not need to run code to see changes. You can make reuse of class in any other project to make button circular.

More about IBDesignable.

Upvotes: 13

jay soni
jay soni

Reputation: 19

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)

Upvotes: 0

Related Questions