我正在创建一个自定义 UIControl 对象,详细信息here http://www.thinkandbuild.it/how-to-build-a-custom-control-in-ios/。除了触摸区域外,一切都运行良好。
我想找到一种方法将触摸区域限制为控件的一部分,在上面的示例中,我希望将其限制为仅黑色圆周而不是整个控件区域。
任何想法?
干杯
您可以覆盖 UIView 的pointInside:withEvent: https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW2拒绝不必要的触摸。
这是一个检查触摸是否发生在视图中心周围的环中的方法:
- (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 值。
所有这一切都取决于您如何建立控制。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)