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

时间:2011-10-31 14:04:38

标签: iphone ios ipad uiimageview uibutton

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

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或ScrollView的子视图,它是ImageView的父级。如果我像[self addSubView:btn]那样制作Scrollview的按钮子视图;它显示在正确的位置并且是可点击的,但问题是它是在队列中的所有图像上创建的,因为我将它作为父视图的子视图,即scrollview。否则,如果我将其视为子视图的子视图,即ImageView,它对于每个图像都是唯一的,但仍然显示在所有图像上且不可点击:/

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

提前致谢。

此致

wahib

1 个答案:

答案 0 :(得分:2)

你必须创建一个额外的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];

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