Search code examples
xcodeuibuttonuistoryboardswift4ios11

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


Solution

  • 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.