UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTapTap:)];
[self.view1 addGestureRecognizer:tapGesture];
[self.view2 addGestureRecognizer:tapGesture];
[tapGesture release];

在上面的代码中,只能识别view2上的点击。如果我注释掉第三行,那么点击view1会被识别。如果我是对的,你只能使用手势识别器一次,我不确定这是一个错误还是它只是需要一些更多的文档。


当前回答

每次你添加一个指向相同func的手势识别器时,重写(重新创建)你的gesturerecogize。 在下面的情况下,它是有效的。我正在使用IBOutletCollection

斯威夫特2:

@IBOutlet var topicView: [UIView]!

override func viewDidLoad() {
        for view in self.topicView as [UIView] {
        view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "viewClicked:"))
    }
}

func viewClicked(recognizer: UITapGestureRecognizer) {
    print("tap")
}

其他回答

我们可以做一些像这样的事情,这很简单

1)在控制器中创建如下函数(此函数将返回GestureRecognizer)

-(UITapGestureRecognizer*)setRecognizer{
     UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openProfile)];
     [gestureRecognizer setNumberOfTapsRequired:1];
     return gestureRecognizer;
}

2)现在在多个视图中设置这个识别器

[self.view1 addGestureRecognizer:[self setRecognizer]]; 
[self.view2 addGestureRecognizer:[self setRecognizer]];

对于Swift 3,如果有人需要这个: 基于Bhavik Rathod的回答。

 func setGestureRecognizer() -> UIPanGestureRecognizer {

        var panRecognizer = UIPanGestureRecognizer()

        panRecognizer = UIPanGestureRecognizer (target: self, action: #selector(pan(panGesture:)))
        panRecognizer.minimumNumberOfTouches = 1
        panRecognizer.maximumNumberOfTouches = 1
        return panRecognizer
    }

        ///set the recognize in multiple views
        view1.addGestureRecognizer(setGestureRecognizer())
        view2.addGestureRecognizer(setGestureRecognizer())

UIGestureRecognizer用于单个视图。我同意文件是参差不齐的。UIGestureRecognizer只有一个视图属性,会泄露信息:

视图 手势识别器附加到的视图。(只读) @property(非原子,只读)UIView *view 你附加(或添加)一个手势识别器到一个UIView对象 使用addGestureRecognizer: 方法。

如果你有固定的视角,我建议你这样做

[self.view1 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTapTap:)]];
[self.view2 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTapTap:)]];

这样可以减少多个不同的无用变量

我使用下面的方法来解决这个问题。

for (UIButton *aButton in myButtons) {

            UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
            longPress.minimumPressDuration=1.0;
            [aButton addGestureRecognizer:longPress];
            [longPress release];

}

然后在我的handleLongPress方法中,我只是设置一个UIButton等于手势识别器的视图,并根据该按钮分支我所做的事情

- (void)handleLongPress:(UILongPressGestureRecognizer*)gesture {
    if ( gesture.state == UIGestureRecognizerStateEnded ) {
        UIButton *whichButton=(UIButton *)[gesture view];
        selectedButton=(UIButton *)[gesture view];
    ....
}