Luke Patterson Luke Patterson - 1 year ago 114
Swift Question

Active clickable area for UIButton with rounded corners?

So I have created a button with a border in my storyboard.
enter image description here

and then I rounded its corners and added a border color:

button.layer.cornerRadius = button.bounds.size.width / 2
button.layer.borderColor = greenColor

So the runtime result looks like this:
enter image description here

However the user can tap slightly outside the area of the button (where the corners used to be) and still call the button function. Is there a way to restrict the enabled area of the button to just be the circle?

Answer Source

So I figured it out. Basically I have to detect the touch on the button, and then calculate the distance between the touch and the center of the button. If that distance is less than the radius of the circle (the width of the button / 2) then the tap was inside the circle.

Here's my code:

 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let radius:CGFloat = (self.frame.width / 2)
    var point:CGPoint = CGPoint()

    if let touch = touches.first {
        point = touch.locationInView(self.superview)

    let distance:CGFloat = sqrt(CGFloat(powf((Float( - point.x)), 2) + powf((Float( - point.y)), 2)))

    if(distance < radius) {
        super.touchesBegan(touches, withEvent: event)