1

So my custom button looks like this:

override func drawRect(rect: CGRect) {
    let mask = CAShapeLayer()
    mask.frame = self.layer.bounds

    let width = self.layer.frame.size.width
    let height = self.layer.frame.size.height

    let path = CGPathCreateMutable()
    CGPathMoveToPoint(path,nil,width/2, 0)
    CGPathAddLineToPoint(path,nil,width, height/2)
    CGPathAddLineToPoint(path,nil,width/2, height)
    CGPathAddLineToPoint(path,nil, 0, height/2)

    mask.path = path
    self.layer.mask = mask
}

I've added the button to a UIView in Storyboard, and subclassed it to this UIButton subclass. I set the background to blue in Storyboard.

The result:

The result:

The problem is then I click around the corners (the white space, as if the button was still being recognised as a square), it is still clickable. This is an issue because I want to add multiple shapes like this next to each other, so I don't want any of the Buttons to block each other out. enter image description here

Glenncito
  • 902
  • 1
  • 10
  • 23
  • You cant. Because, you are not rotating the button frame,instead you are creating a custom image for your button. The red area is still considered as button frame. Try rotating the button,instead of writing the custom code. – Teja Nandamuri Oct 05 '15 at 17:18

2 Answers2

2

You can override the pointInside function in your custom UIButton to control when a touch in your view's bounds should be considered a hit.

override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
    let width = bounds.size.width
    let height = bounds.size.height

    // Make a UIBezierPath that contains your clickable area
    let path = UIBezierPath()
    path.moveToPoint(CGPoint(x: width / 2, y: 0))
    path.addLineToPoint(CGPoint(x: width, y: height / 2))
    path.addLineToPoint(CGPoint(x: width / 2, y: height))
    path.addLineToPoint(CGPoint(x: 0, y: height / 2))
    path.closePath()

    // Let a hit happen if the point touched is in the path
    return path.containsPoint(point)
}

See also

Community
  • 1
  • 1
Edman
  • 5,335
  • 29
  • 32
1

How about adding UITapGestureRecognizer to the button view, get the coordinate of tap and convert the coordinates to parent view coordinate and compare if its in the twisted cube.

//sender being the UITapGestureRecognizer
let coordinate = containerView.convertPoint(sender.locationInView(ContainerView), toCoordinateFromView: containerView)
Lukas
  • 3,423
  • 2
  • 14
  • 26