iOS将tapGesture添加到多个视图 [英] iOS adding tapGesture to multiple Views

查看:166
本文介绍了iOS将tapGesture添加到多个视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在主视图中定义了多个视图。我想为所有这些视图添加单击手势。下面是我编写的代码,但这会将轻击手势注册到我添加的最后一个视图。因此,在下面的代码中,点击仅针对 messagesView &不适用于其他观点。我有两个问题:

I have multiple views defined in my main view. I want to add single tap gesture to all these views. Below is the code I have written, but this registers a tap gesture to the last view that I add. So in the code below, tap is registered only for messagesView & not for other views. I have 2 questions:


  1. 如何在多个视图中注册相同的tapGesture?

  1. How do I register the same tapGesture to multiple Views?

让我们假设我的工作正常,现在这些视图中的所有单击都会转到名为 oneTap 的相同函数。在此功能中,我如何区分水龙头来自哪个视图?

Lets assume I get this working, now all single taps from these views goto the same function called oneTap. In this function how do I distinguish from which view the tap is coming?

代码:

@synthesize feedsView, peopleView, messagesView, photosView;

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(oneTap:)];
    [singleTap setNumberOfTapsRequired:1];
    [singleTap setNumberOfTouchesRequired:1];
    [feedsView addGestureRecognizer:singleTap];
    [peopleView addGestureRecognizer:singleTap];
    [messagesView addGestureRecognizer:singleTap];
    //[photosView addGestureRecognizer:singleTap];
    [singleTap release];

    return;
}


推荐答案

我遇到了同样的问题它只添加到最后一个视图。可能有更好的解决方案,但我只为每个视图创建了一个标记手势,并将它们链接到相同的选择器方法(在您的情况下为 oneTap:)。为了区分哪个视图激活了该方法,您只需标记您的视图, feedsView.tag = 0; peopleView.tag = 1; 等等。然后当调用该方法时:

I had the same problem where it only added to the last view. There might be a better solution, but I just created a tag gesture for each view and linked them to the same selector method (oneTap: in your case). In order to distinguish which view activated the method, you can just tag your views, feedsView.tag = 0; peopleView.tag = 1; and so on. Then when the method is called:

- (void)oneTap:(UIGestureRecognizer *)gesture {
    int myViewTag = gesture.view.tag;  // now you know which view called
    // use myViewTag to specify individual actions;
}

这篇关于iOS将tapGesture添加到多个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆