如何检测几个UIViews之间的触摸?

时间:2014-06-16 15:22:23

标签: ios iphone objective-c uiview touch

案例是我在主屏幕上有几个UIViews,我就像桌子一样一个一个地安排它们。 我想实现一个函数,我随机点击UIView并在每个函数之间移动我的手指(如悬停)。当我触摸上次触摸的UIView时,设备会振动。

到现在为止,我试图使用"

  • (无效)touchesMoved"实现它的方法,但它没有工作。我给每个uiview一个特定的标签。当我打电话给#34; - (无效)触动开始"方法,我将更新当前的标签号。我期待" - (void)touchesMoved"方法可以帮助我刷新视图的当前标记,但它没有。它仍然是我在&#34中更新的相同标签号码; - (void)touchesBegan"方法

这是代码。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    touch = [[event allTouches] anyObject];
    currentTag = touch.view.tag;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    touch = [[event allTouches] anyObject];
    NSLog(@"%ld", (long)touch.view.tag);
    if (touch.view.tag != currentTag) {
        NSLog(@"Vibrate");
        currentTag = touch.view.tag;
    }
}

希望得到一些帮助〜

谢谢你。

2 个答案:

答案 0 :(得分:2)

将您的观点添加到容器视图并覆盖它touchesMoved等,并自行检查边界:

-(void)touchesMoved: (NSSet *)touches withEvent: (UIEvent *)event {
    CGPoint location = [[touches anyObject] locationInView:self];

    for (UIView *view in self.subviews) {
        if(CGRectContainsPoint(view.frame, location)){
            if (view.tag != currentTag) {
                NSLog(@"Vibrate");
                currentTag = touch.view.tag;
            }
        }
    }
}

答案 1 :(得分:0)

您也可以使用scrollview执行此操作。 您可以在scrollview中创建切片。请在下面找到代码。

UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,view.frame.size.width,view.frame.size.height)];     scrollView.backgroundColor = [UIColor clearColor];     [self.view addSubview:scrollView];

int column = 0;
for(int i = 0; i < data.count; ++i) {


    UIView *tile = [[UIView alloc]initWithFrame:CGRectMake(column*230+24, 20, 200, 160)]];

    tile.backgroundColor = [UIColor clearColor];
    tile.tag = i+1 ;

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    tapGesture.numberOfTapsRequired = 1;
    [tile addGestureRecognizer:tapGesture];


    [scrollView addSubview:tile];


    column++;



}


[scrollView setContentSize:CGSizeMake(column*225+24,view.frame.size.height)];

}

如果需要澄清,请告诉我。快乐编码