1

我有一个缩略图网格,当其中一个被触摸时,我想显示整个图像。现在,我知道 UIImageView 不响应触摸事件,但正如这个答案中所建议的,我创建了一个 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];
}

好的。所以我创建了一个自定义按钮,设置它的框架以匹配图像框架,告诉它响应内部的修饰以及如何响应,并将其添加到图像的子视图中。但是当我运行它时,我什么也得不到。“图像被窃听”。没有出现在控制台中,所以我知道消息没有被发送。我在这里做错了什么?

非常感谢您的帮助。

4

3 回答 3

3

默认情况下,UIImageView 的 userInteractionEnabled 属性设置为 NO

添加这一行

imageView.userInteractionEnabled = YES;
于 2012-08-01T15:30:03.727 回答
1

尝试

imageView.userInteractionEnabled = YES;

这是从 UIView 继承的属性,但根据 Apple 的文档,UIImageView 将其默认值更改为 NO,忽略所有事件。

于 2012-08-01T15:29:55.300 回答
1

除了设置之外imageView.userInteractionEnabled = YES,您还可以完全取消按钮并添加一个UITapGestureRecognizerUIImageView处理水龙头。它看起来像:

UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];
[imageView addGestureRecognizer:recognizer];
于 2012-08-01T15:37:17.703 回答