2012-08-01 54 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];