2

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

sriram hegde
  • 2,301
  • 5
  • 29
  • 43
  • 2
    Possible duplicate of [How to create a circular button in Swift?](https://stackoverflow.com/questions/26050655/how-to-create-a-circular-button-in-swift) – Alladinian Mar 01 '18 at 11:19

3 Answers3

13

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.

technerd
  • 14,144
  • 10
  • 61
  • 92
  • 1
    This will correctly create a circular button, but note that the target area will remain unchanged - i.e. it will still be square and therefore tappable outside the actual button. –  Jun 01 '18 at 15:08
4

Very simple and easy.

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

this will surely going to work. Eat sleep code repeat

Raghib Arshi
  • 717
  • 8
  • 12
0
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)
jay soni
  • 19
  • 6