2011-10-31 57 views
0

我正在使用PhotoScroller项目并希望以编程方式在imageViews上创建按钮。 ImageView是ScrollerView的子视图。我的代码片段如下所示:如何在动态ImageView上创建动态按钮,同时保持唯一性

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

任何1可以引导我如何使它可点击并保持动态按钮和独特的图像,以便在队列中的每个图像上的各个位置都有不同的按钮。

在此先感谢。

问候,

wahib

回答

2

你必须同时包含的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]; 

注意与内存泄漏创建一个额外的UIView。你的代码中有很多未使用的保留。