我有自定义的 UIButtons,它旋转了 45 度 - 我该如何做到只有实际形状内的 space 是可点击的?

I have custom UIButtons which are rotated 45 Degrees - how do I make it so that only the space within the actual shape is clickable?

所以我的自定义按钮如下所示:

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
}

我已将按钮添加到 Storyboard 中的 UIView,并将其子类化到此 UIButton 子类。我在故事板中将背景设置为蓝色。

结果:

问题是我点击了角落(白色 space,好像按钮仍然被识别为正方形),它仍然是可点击的。这是一个问题,因为我想添加多个像这样的形状并排放置,所以我不希望任何按钮相互阻挡。

您可以覆盖自定义 UIButton 中的 pointInside 函数来控制何时应将视图边界中的触摸视为一次点击。

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)
}

另见

  • Allowing interaction with a UIView under another UIView

如何将 UITapGestureRecognizer 添加到按钮视图,获取点击的坐标并将坐标转换为父视图坐标并比较它是否在扭曲的立方体中。

//sender being the UITapGestureRecognizer
let coordinate = containerView.convertPoint(sender.locationInView(ContainerView), toCoordinateFromView: containerView)