2012-08-01 112 views
1

我有一個縮略圖圖像的網格,當它們中的一個被觸摸時,我想顯示整個圖像。現在,我知道UIImageView不響應觸摸事件,但正如this answer中所建議的那樣,我創建了一個UIButton來處理事件。見下面的代碼:圖像視圖沒有響應觸摸事件

- (void)displayImage 
{ 
     NSUInteger i = 0; // The actual code is different and works; this is just for brevity's sake. 

     // UILazyImageView is a subclass of UIImageView 
     UILazyImageView *imageView = [[UILazyImageView alloc] initWithURL:[NSURL URLWithString:[[[self images] objectAtIndex:i] thumbnailUrl]]]; 

     UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     [imageButton setFrame:[imageView frame]]; 
     [imageButton addTarget:self action:@selector(imageTapped:) forControlEvents:UIControlEventTouchUpInside]; 
     [imageView addSubview:imageButton]; 

     [[self containerView] addSubview:imageView]; 
     [imageView release]; 
    } 
} 

- (void)imageTapped:(id)sender 
{ 
    NSLog(@"Image tapped."); 

    // Get the index of sender in the images array 
    NSUInteger index = 0; // Don't worry, I know. I'll implement this later 

    FullImageViewController *fullImageViewController = [[[FullImageViewController alloc] initWithImageURL:[NSURL URLWithString:[[[self images] objectAtIndex:index] url]]] autorelease]; 
    [[self navigationController] pushViewController:fullImageViewController animated:YES]; 
} 

好的。所以我創建了一個自定義按鈕,設置其框架以匹配圖像框架,告訴它響應內部觸摸以及如何響應,並將其添加到圖像的子視圖中。但是當我運行這個時,我什麼也得不到。 「圖片點擊」。沒有出現在控制檯中,所以我知道該消息沒有被髮送。我在這裏做錯了什麼?

非常感謝您的幫助。

回答

3

默認的UIImageView有其userInteractionEnabled屬性設置爲NO

此行

imageView.userInteractionEnabled = YES; 
1

嘗試

imageView.userInteractionEnabled = YES; 

這是UIView的繼承財產,但按照蘋果的文檔,UIImageView的改變其默認值爲NO,忽略所有的事件。

1

除了增加設置imageView.userInteractionEnabled = YES,可以完全消除按鈕,添加一個UITapGestureRecognizerUIImageView處理水龍頭。它看起來像這樣:

UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)]; 
[imageView addGestureRecognizer:recognizer];