skip to Main Content

My goal is to create a button with fully rounded corners (half a circle at each side). It should look something like this:

enter image description here

In the user defined runtime attributes I’ve set layer.cornerRadius as KeyPath and 50 as Value (also tried 49). Also, I’ve set the the “Clip Subviews” option to yes (like in this answer: UIlabel layer.cornerRadius not working in iOS 7.1)
However, the compiled result looks like this on my iPhone 5c (iOS 9.2.1):

enter image description here

(The images are made in photoshop but that’s exactly how it looks like)

The corners are rounded but there is clearly an anchorpoint missing. Any suggestion on how to get the desired result?

3

Answers


  1. Try this if you want to have a dynamic approach rather than using fixed values.

      let button = UIButton()
      button.layer.cornerRadius = button.frame.size.height/2-1
    
    Login or Signup to reply.
  2. The cornerRadius value does not update automatically depending on button height, so, when specifying it from storyboard/xib, you have to make sure the value is exactly the half of the button height.

    Typically this is achieved by setting the button height to a constant (using a height constraint) and setting cornerRadius to half of that constant (e.g. for height 100 you want cornerRadius with value 50).

    If you want an autoupdating solution, the easiest solution is to subclass UIButton and override layoutSubviews:

    override func layoutSubviews() {
       super.layoutSubviews()
    
       self.layer.cornerRadius = self.frame.size.height / 2.0
    }
    

    Then in xib/storyboard you can change the class of your button to your custom class.

    Login or Signup to reply.
  3. For me the below worked better than anything else
    Create a class for your rounded button and subclass UIButton.

    class RoundedButton: UIButton {
    
     //add your title color and background color outside the below override method
     
     override func draw(_ rect: CGRect) {
        layer.cornerRadius = frame.height / 2.0
        clipsToBounds = true
     }   
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search