我正在使用XCode 4.5.1。以編程方式創建的UIImageView上未觸發的UITapGestureRecognizer
我的.h文件和.m文件開始在viewDidLoad
添加<UIGestureRecognizerDelegate>
@interface FirstViewController()
@property (nonatomic, strong) UIImageView *img1;
@end
然後,創建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循環中分別具有手勢識別每一個ImageView的
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);
}
}
我試過你發佈的代碼,它對我來說工作正常。我正在回調。如果您使用多個圖像,則需要創建不同的UITapGestureRecognizer。對於一張圖片,代碼應該可以正常工作,請檢查是否有任何東西是零,或者你的代碼沒有被調用。 – Amit 2013-04-23 10:02:23
這是行之有效的,確保在你將它設置爲-30時檢查你正在點擊的圖像,檢查一下。 – 2013-04-23 10:05:05
@ amit3117 ....我嘗試使用for循環,爲每個圖像添加單獨的gesturerecognizer,但在我的結尾不起作用。 – eagle 2013-04-23 10:15:01