iphone - 如何在保持唯一性的同时在动态 ImageView 上创建动态按钮

标签 iphone ios ipad uiimageview uibutton

我正在使用 PhotoScroller 项目并希望以编程方式在 imageViews 上创建按钮。 ImageView是ScrollerView的子View。我的代码片段如下所示:

imageView = [[UIImageView alloc] initWithImage:image]; //initWithImage:image

//imageView.tag = i; // tag our images for later use when we place them in serial form
[imageView setContentMode:UIViewContentModeScaleToFill]; //though it has no impact
imageView.userInteractionEnabled = YES; //to enable touch interaction with image

[self addSubview:imageView];

UIButton *btn = [[UIButton buttonWithType:UIButtonTypeContactAdd] retain]; //Plus icon   button

btn.frame = CGRectMake(215, 550, 100, 100);
[btn addTarget:self action:@selector(onClickHotSpotButton)           forControlEvents:UIControlEventTouchUpInside]; //it wasnt working

[self addSubview:btn]; //Buttons are clickable but shows button on all images**

//[imageView addSubview:btn]; //Buttons are not clickable and are shown on all images

我现在有两个选择。我是否将我的按钮设为 ImageView 的 subview 或作为 ImageView 父级的 ScrollView。如果我使 Scrollview 的按钮 subview 像 [self addSubView:btn];它显示在正确的位置并且可以点击,但问题是它是在队列中的所有图像上创建的,因为我正在将它作为父 View 的 subview ,即 ScrollView 。否则,如果我将其设为 subview 的 subview ,即 ImageView,它对于每个图像都是唯一的,但它仍然显示在所有图像上并且不可点击:/

任何人都可以指导我如何使其可点击并保持动态按钮和图像之间的链接唯一,以便我在队列中每个图像的不同位置有不同的按钮。

提前致谢。

问候,

瓦希布

最佳答案

你必须创建一个额外的 UIView 来包含 UIImageView 和 UIButton

UIView* imageContainer = [[UIView alloc] initWithFrame:CGRectMake(0,0,1000,1000)] autorelease];
UIImageView* imageView = [[[UIImageView alloc] initWithImage:image] autorelease];

[imageView setContentMode:UIViewContentModeScaleToFill]; //though it has no impact
imageView.userInteractionEnabled = YES; //to enable touch interaction with image

[imageContainer addSubview:imageView];

UIButton *btn = [[UIButton buttonWithType:UIButtonTypeContactAdd] retain]; //Plus icon   button

btn.frame = CGRectMake(215, 550, 100, 100);
[btn addTarget:self action:@selector(onClickHotSpotButton) forControlEvents:UIControlEventTouchUpInside]; //it wasnt working

[imageContainer addSubview:btn];
[self addSubview:imageContainer];

小心内存泄漏。您的代码中有很多未使用的保留。

关于iphone - 如何在保持唯一性的同时在动态 ImageView 上创建动态按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7954773/

相关文章:

iOS 7 自定义键盘 UIView 触地事件在底行延迟

android - 您可以在不编写任何 native 代码的情况下访问智能手机上的蓝牙吗?

ios - 用于立即分配变量的 block 的运行时开销

iPhone/iPad HTTP 流媒体库或服务器

iphone - 访问无法修改的父类扩展中定义的 Obj-C 属性

iphone - iOS : Image get rotated 90 degree after saved as PNG representation data

ios - 在 iTunesConnect 所有权转移后推送通知仍然有效

ios - NSNumber 类型的托管属性?没有初始化为 nil

ios - UIButton 中的截断斜体文本?

ios - 使用自定义高度在 UINavigationBar 中垂直居中元素