在自定义UIControl对象中定义自定义触摸区域

我正在创建一个自定义的UIControl对象,详见此处 。 除触摸区外,一切运作良好。

我想找到一种方法将触摸区域限制为仅控制的一部分,在上面的示例中,我希望它仅限于黑色圆周而不是整个控制区域。

任何想法? 干杯

您可以覆盖UIView的pointInside:withEvent:来拒绝不需要的触摸。

这是一种方法,用于检查触摸是否发生在视图中心周围的环中:

 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { UITouch *touch = [[event touchesForView:self] anyObject]; if (touch == nil) return NO; CGPoint touchPoint = [touch locationInView:self]; CGRect bounds = self.bounds; CGPoint center = { CGRectGetMidX(bounds), CGRectGetMidY(bounds) }; CGVector delta = { touchPoint.x - center.x, touchPoint.y - center.y }; CGFloat squareDistance = delta.dx * delta.dx + delta.dy * delta.dy; CGFloat outerRadius = bounds.size.width * 0.5; if (squareDistance > outerRadius * outerRadius) return NO; CGFloat innerRadius = outerRadius * 0.5; if (squareDistance < innerRadius * innerRadius) return NO; return YES; } 

要检测更复杂形状上的其他命中,您可以使用CGPath来描述形状并使用CGPathContainsPoint测试。 另一种方法是使用控件的图像并测试像素的alpha值。

所有这些都取决于你如何构建控件。