将事件添加到 xcode 中的图像时出错

Posted

技术标签:

【中文标题】将事件添加到 xcode 中的图像时出错【英文标题】:error in adding a event to an image in xcode 【发布时间】:2011-03-26 13:25:16 【问题描述】:

我想向图像添加事件。但如果我添加这意味着它会给出警告:UIImage 可能不会响应控制事件的 addtarget 操作。如何更正此代码。

这是我的代码 UIImageView *image;

UIImage *image1=[UIImage imageNamed:@"left_arrow.png"]; image=[[UIImageView alloc]initWithImage:image1]; image.frame=CGRectMake(100,410,30,30);

[image1 addTarget:self action:@selector(buttonPressed2:)forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:image];

【问题讨论】:

【参考方案1】:

如果您不想使用额外的按钮,可以将UITapGestureRecognizer 添加到 imageView。

像这样:

UITapGestureRecognizer *tapGesture = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonPressed2:)] autorelease];
[imageView addGestureRecognizer:tapGesture];
[imageView setUserInteractionEnabled:YES];

但这更像是UIControlEventTouchDown 事件

【讨论】:

【参考方案2】:

您需要在 UIImageView 之上创建一个透明的自定义 UIButton。该按钮将处理事件。 UIImageView 可以做到。

UIButton *btn  = [[[UIButton alloc] initWithFrame:imageView.frame] autorelease];
btn.buttonType=UIButtonTypeCustom;
[btn addTarget:...];

【讨论】:

以上是关于将事件添加到 xcode 中的图像时出错的主要内容,如果未能解决你的问题,请参考以下文章