使用UIViews数组检测UIScrollView层中UIView的触摸

时间:2011-09-15 20:03:09

标签: uiview uiscrollview touch touchesbegan cgpoint

原谅我,我对此有点新意。

我正在尝试检测类似MoveMe示例的触摸 - 只有我将一个UIViews(studentCell)数组放入一个名为studentCellArray的NSMutableArray中。

[self.studentCellArray addObject:self.studentCell];

当我有一次触摸时,我想让程序足够智能,以便知道它是否触及了数组中的任何UIViews,以及它是否可以执行某些操作。

以下是touchesBegan:method中的代码。

//prep for tap
int ct = [[touches anyObject] tapCount];
NSLog(@"touchesBegan for ClassRoomViewController tap[%i]", ct);
if (ct == 1) {
    CGPoint point = [touch locationInView:[touch view]];
    for (UIView *studentCard in self.studentCellArray) {
        //if I Touch a Card then I grow card...

    }
    NSLog(@"I am here[%@]", NSStringFromCGPoint(point));
}

我不知道如何访问视图并触摸它们。

1 个答案:

答案 0 :(得分:1)

我通过为数组中的每个UIView分配UIPanGestureRecognizer来“解决”这个问题。

这可能不是最好的方法,但我现在可以在屏幕上移动它们。

以下是代码:

for (int x = 0; x < [keys count]; x++) {
                UIPanGestureRecognizer *pGr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragging:)];
                UIView *sca =  [self.studentCellArray objectAtIndex:x];

                [sca addGestureRecognizer:pGr];
                [pGr release];
            }

这是我使用的“拖动”方法。我已将屏幕划分为三分之一,并且有一个动画可以将UIViews捕捉到一个点,如果碰巧超过阈值。我希望这给了一些好主意。如果你能看到更好的方法,请帮忙。

- (void) dragging:(UIPanGestureRecognizer *)p{
UIView *v = p.view;

if (p.state == UIGestureRecognizerStateBegan || p.state == UIGestureRecognizerStateChanged) {
    CGPoint delta = [p translationInView:studentListScrollView];
    CGPoint c = v.center;
    c.x += delta.x;
    //c.y += delta.x;
    v.center = c;
    [p setTranslation:CGPointZero inView:studentListScrollView];

}
if (p.state == UIGestureRecognizerStateEnded) {
    CGPoint pcenter = v.center;
    //CGRect frame = v.frame;
    CGRect scrollFrame = studentListScrollView.frame;
    CGFloat third = scrollFrame.size.width/3.0;
    if (pcenter.x < third) {
        pcenter = CGPointMake(third/2.0, pcenter.y);
        //pop the view
        [self showModalDialog:YES perfMode:YES andControlTag:[studentCellArray indexOfObjectIdenticalTo:p.view]];
    }
    else if (pcenter.x >= third && pcenter.x < 2.0*third) {
        pcenter = CGPointMake(3.0*third/2.0, pcenter.y);

    }
    else 
    {
        pcenter = CGPointMake(5.0 * third/2.0, pcenter.y);
        //pop the view
        [self showModalDialog:YES perfMode:YES andControlTag:[studentCellArray indexOfObjectIdenticalTo:p.view]];
    }

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.2];
    v.center = pcenter;
    [UIView commitAnimations];
}

}

编辑:将[studentCellArray indexOfObjectIdenticalTo:p.view]添加到andControlTag会给我触摸视图数组中的位置,这样我就可以在我的模态对话框中传递它以显示相应的信息。