我有一个缩略图的网格,当其中一个被触摸时,我想显示整个图像。现在,我知道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];
}
确定。因此,我创建了一个自定义按钮,设置其框架以匹配图像框架,告诉它响应内部修饰和如何响应,并将其添加到图像的子视图中。但是当我跑这个时,我什么都没得到。 “图像轻拍”。没有出现在控制台中,所以我知道该消息没有被发送。我在这里做错了什么?
非常感谢你的帮助。
答案 0 :(得分:3)
默认情况下,UIImageView的userInteractionEnabled属性设置为NO
添加此行
imageView.userInteractionEnabled = YES;
答案 1 :(得分:1)
尝试
imageView.userInteractionEnabled = YES;
这是一个继承自UIView的属性,但根据Apple的文档,UIImageView将其默认值更改为NO,忽略所有事件。
答案 2 :(得分:1)
除了设置imageView.userInteractionEnabled = YES
之外,您还可以完全取消按钮,并为UITapGestureRecognizer
添加UIImageView
来处理点按。它看起来像是:
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];
[imageView addGestureRecognizer:recognizer];