有一個網格視圖的圖片,怎麼為每個圖片添加一個點擊事件?
- (void)viewDidLoad
{
[super viewDidLoad];
int Columns = 3;
int Rows=5;
int space = 10;
int width = (self.view.frame.size.width-(Columns)*space)/Columns;
int height = width;
int x = space;
int y = space;
UIScrollView *Scroll=[[UIScrollView alloc]initWithFrame:CGRectMake(x, y,self.view.frame.size.width, self.view.frame.size.height) ];
[Scroll setContentSize:CGSizeMake(Columns*(space+width)+space, Rows*(space+(self.view.frame.size.height-(Columns)*space)/Columns)+space)];
Scroll.backgroundColor=[UIColor yellowColor];
Scroll.showsVerticalScrollIndicator=YES;
for(int i=1 ;i<30;i++)
{
j++;
NSLog(@"j= %i",j);
label=[[UILabel alloc]initWithFrame:CGRectMake(x,y,width,height)];
label.backgroundColor=[UIColor blueColor];
image= [[UIImageView alloc] initWithFrame:CGRectMake(x,y,width,height)];
image.image = [UIImage imageNamed:
[NSString stringWithFormat:@"image%02ds.jpg", i+1]];
[Scroll addSubview:label];
if (i%Columns == 0) {
y += space+height;
x = space;
} else {
x+=space+width;
}
[Scroll addSubview:image];
}
[self.view addSubview:Scroll];
}
可以用UITapGestureRecognizer
實現
UITapGestureRecognizer *tapRecognizer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];
imageView.tag=TAG; //Tag your imageview to identify in call back
[imageView addGestureRecognizer:tapRecognizer];
[tapRecognizer release]; //If not ARC
回調函數如下.
-(void)imageTapped:(UITapGestureRecognizer *)tapRecognizer
{
if ([tapRecognizer.view isKindOfClass:[UIImageView class]]) {
if (tapRecognizer.view.tag==TAG) { //Identify image view tag
//Your code for image tap action
}
}
}