找到点击的视图

时间:2011-02-25 08:15:04

标签: iphone

我有一个视图控制器,其中有几个uiview对象。我需要知道哪个用户点击了uiview。这怎么可能?任何指导都会有很大的帮助......

感谢
的Pankaj

4 个答案:

答案 0 :(得分:6)

以下是您可以做的事情以获得您想要的......在此示例中,我创建了7个视图

UITapGestureRecognizer* gestureRecognizer;
UIView* myView;
for (int i = 0; i < 8; i++) 
{
    gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doSomthing:)];
    gestureRecognizer.numberOfTapsRequired = 1;//or what ever you want

    myView = [[UIView alloc] initWithFrame:CGRectMake(10, i*30, 30, 28)];
    myView.backgroundColor = [UIColor redColor];
    myView.tag = 100+i;
    [self.view addSubview:myView];
    [myView addGestureRecognizer:gestureRecognizer];
    [myView release];
    [gestureRecognizer release];
}

现在你需要实现像这样的方法

-(void)doSomthing:(id)sender
{
    UIView* temp = [(UITapGestureRecognizer*)sender view];
    // here you get the view you wanted
    NSLog(@"view number :%d",temp.tag);
}

我认为这应该可以帮到你

答案 1 :(得分:1)

为每个视图设置标记以跟踪它们。

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    // We only support single touches, so anyObject retrieves just that touch from touches
    UITouch *touch = [touches anyObject];
    NSLog(@"view %i", [touch view].tag);
}

答案 2 :(得分:0)

您可以向uiview对象添加手势以查找已触摸的对象。见文档。

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIGestureRecognizer_Class/Reference/Reference.html

具体代码只需评论。

答案 3 :(得分:0)

你可以在每个视图的顶部添加一个带标签的自定义按钮。然后你可以根据按钮标签知道哪个视图被点击。

请看看这个。这可能有所帮助。

http://www.iphonedevsdk.com/forum/iphone-sdk-development/13041-touch-event-subview.html