Make only points within UIBezierPath button selectable

My swift code features a custom shape button made from a UIBezierPath. The code should only call the func press if it the user touches the red part if the user touches the green part the func press should not be called. Right now if you touch the green part the func is still called.

import UIKit

class ViewController: UIViewController {
    let customButton = UIButton(frame: CGRect(x: 100.0, y: 100.0, width: 200.0, height: 140.0))
    override func viewDidLoad() {
        // Do any additional setup after loading the view.
        customButton.backgroundColor =
        let aPath = UIBezierPath()
        aPath.move(to: CGPoint(x: 50, y: 0))
        aPath.addLine(to: CGPoint(x: 200.0, y: 40.0))
        aPath.addLine(to: CGPoint(x: 160, y: 140))
        aPath.addLine(to: CGPoint(x: 40.0, y: 140))
        aPath.addLine(to: CGPoint(x: 0.0, y: 40.0))
        let layer = CAShapeLayer()
        layer.fillColor =
        layer.strokeColor =
        layer.path = aPath.cgPath
        customButton.addTarget(self, action: #selector(press), for: .touchDown)
    @objc func press(){


This topic was automatically closed after 166 days. New replies are no longer allowed.