我正在使用 XCode 4.5.1 。
我<UIGestureRecognizerDelegate>
在 .h 文件和 .m 文件的开头添加了
@interface FirstViewController ()
@property (nonatomic, strong) UIImageView *img1;
@end
然后在,以编程方式viewDidLoad
创建UIImageView
self.img1 = [[UIImageView alloc] initWithFrame:CGRectMake(50, -30, 44, 44)];
[self.img1 setImage:[UIImage imageNamed:@"image1.png"]];
[self.img1 setAlpha:0.8];
[self.img1 setHidden:NO];
[self.img1 setUserInteractionEnabled:YES];
[self.img1 setTag:901];
接着
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(guessTapObject:)];
tap.numberOfTapsRequired = 1;
tap.numberOfTouchesRequired = 1;
tap.delegate = self;
[self.img1 addGestureRecognizer:tap];
[self.view addSubview:self.img1];
[self.view bringSubviewToFront:self.img1];
最后
- (void)guessTapObject:(UITapGestureRecognizer *) gesture
{
// guessing the image
UIImageView *tapImageView = (UIImageView*) gesture.view;
NSLog(@"Gesture Tag: %d", tapImageView.tag);
}
我有 4 个不同的图像,并如上所述以编程方式创建它们。并应用动画将它们从上到下移动。
我希望当用户点击图像时,它应该动画并消失(我知道那个代码)。但是代码没有触发点击事件。我将断点放在guessTapObject
函数的开头,但永远不要去那里。
在UITapGestureRecognizer
声明时,调试显示guessTapObject
附加到识别器以执行点击操作。
请帮忙为什么点击事件没有触发它的选择器方法???
提前感谢您的帮助。
编辑:我还尝试使用 for 循环为每个图像视图分别设置手势识别器
for (UIView * view in self.view.subviews) {
if (view.tag > 900){
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(guessTapObject:)];
tap.numberOfTapsRequired = 1;
tap.numberOfTouchesRequired = 1;
// tap.delegate = self;
[view addGestureRecognizer:tap];
NSLog(@"tapView: %@", tap.view);
NSLog(@"tap: %i", tap.enabled);
}
}