Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclass of UIButton with rounded corners (swift)

Using swift, I'd like like to create a button with rounded corners. To make this re-usable, my preference is to subclass UIButton, and have come up with the following:

import Foundation
import UIKit

class LoginButton: UIButton {

  let corner_radius : CGFloat =  4.0

  override func drawRect(rect: CGRect) {
    super.drawRect(rect)
    self.layer.cornerRadius = corner_radius
  }

}

Unfortunately, this doesn't seem to work as I had hoped, even though it compiles fine. Perhaps I'm missing something - I'm very new to this!

Any ideas?

like image 384
Ben Avatar asked Nov 23 '15 15:11

Ben


People also ask

How do you round the corners of a button in Swift?

To get round corners button using Interface Builder add a Key Path = "layer. cornerRadius" with Type = "Number" and Value = "10" (or other value as required) in the " User Defined RunTime Attribute " of the Identity Inspector of the button.


2 Answers

You need to use clipsToBounds to ensure that the containing view isn't drawn over the corner radius:

self.clipsToBounds = true
like image 139
Swinny89 Avatar answered Oct 15 '22 15:10

Swinny89


You need also to turn on the masksToBounds on the layer:

self.layer.masksToBounds = true
like image 37
Alladinian Avatar answered Oct 15 '22 14:10

Alladinian