我正在使用 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/