2
votes

I am attempting to draw a 'circular/oval/ellipse' custom UIView in iOS (using swift)

I am drawing the UIView using a subclass as follows

import Foundation
import UIKit

class CustomEllipse: UIView {


  override func drawRect(rect: CGRect)
  {
    var ovalPath = UIBezierPath(ovalInRect: rect)
    UIColor.grayColor().setFill()
    ovalPath.fill()
  }

}

This produces output similar to the following

enter image description here

I now need to define a clickable area for this 'CustomEllipse'.

However, when I define a UITapGestureRecognizer for the 'CustomElipse', the black corners seen above are clickable by default.

Is there a way to make just the grey ellipse clickable?

1

1 Answers

2
votes

You can customize the clickable area by overriding pointInside(_: withEvent:) method. By default, the area is the same as bounds rectangle.

In this case, you can use containsPoint() method in UIBezierPath. like this:

class CustomEllipse: UIView {

    var ovalPath:UIBezierPath?

    override func drawRect(rect: CGRect) {
        ovalPath = UIBezierPath(ovalInRect: rect)
        UIColor.grayColor().setFill()
        ovalPath!.fill()
    }

    override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
        return ovalPath?.containsPoint(point) == true
    }
}