我有一个UIScrollView
,其中包含大量相同大小的矩形子视图。然后我需要能够将CGPoint
传递给UIScrollView
,我希望它能够为我提供包含CGPoint
的矩形子视图。这基本上是hitTest:event
,除了hitTest:event:
UIScrollView
一旦CGPoint
超出UIScrollView范围,并且不会调查其中UIScrollView
实际内容。
每个人都在做什么?如何进行测试"在NSArray *rectangles = [self getBeautifulRectangles];
CGFloat rectangleLength;
rectangleLength = 100;
// add some rectangle subviews
for (int i = 0; i < rectangles.count; i++) {
UIView *rectangle = [rectangles objectAtIndex:i];
[rectangle setFrame:CGRectMake(i * rectangleLength, 0, rectangleLength, rectangleLength)];
[_scrollView addSubview:rectangle];
}
[_scrollView setContentSize:CGSizeMake(rectangleLength * rectangles.count, rectangleLength)];
// add scroll view to parent view
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320, rectangleLength)];
[containerView addSubview:_scrollView];
// compute CGPoint to center of first rectangle
CGPoint number1RectanglePoint = CGPointMake(0 * rectangleLength + 50, 50);
// compute CGPoint to center of fifth rectangle
CGPoint number5RectanglePoint = CGPointMake(4 * rectangleLength + 50, 50);
UIView *firstSubview = [containerView hitTest:number1RectanglePoint withEvent:nil];
UIView *fifthSubview = [containerView hitTest:number5RectanglePoint withEvent:nil];
if (firstSubview) NSLog(@"first rectangle OK");
if (fifthSubview) NSLog(@"fifth rectangle OK");
内容视图?
这里有一些代码来说明问题:
{{1}}
输出:第一个矩形确定
答案 0 :(得分:1)
如果滚动滚动视图,我猜您将错误的CGPoint
坐标传递给hitTest:withEvent:
方法导致错误的行为。
传递给此方法的坐标必须位于目标视图坐标系中。我猜您的坐标位于UIScrollView
的superview坐标系中。
您可以在使用CGPoint hitPoint = [scrollView convertPoint:yourPoint fromView:scrollView.superview]
进行命中测试之前转换坐标。
在您的示例中,您让容器视图执行命中测试,但容器只能看到&amp;点击滚动视图的可见部分,因此您的点击失败。
要点击滚动视图的可见区域之外的子视图,您必须直接在滚动视图上执行命中测试:
UIView *firstSubview = [_scrollView hitTest:number1RectanglePoint withEvent:nil];
UIView *fifthSubview = [_scrollView hitTest:number5RectanglePoint withEvent:nil];
答案 1 :(得分:1)
您应该能够遍历scrollview子视图
+(UIView *)touchedViewIn:(UIScrollView *)scrollView atPoint:(CGPoint)touchPoint {
CGPoint actualPoint = CGPointMake(touchPoint.x + scrollView.contentOffset.x, scrollView.contentOffset.y + touchPoint.y);
for (UIView * subView in scrollView.subviews) {
if(CGRectContainsPoint(subView.frame, actualPoint)) {
NSLog(@"THIS IS THE ONE");
return subView;
}
}
//Nothing touched
return nil;
}