我有一个grid view of images
...我如何在代码中进行更改,使其可以针对每张图片进行点击。
如何为每张图片回复点击事件?
- (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];
}
答案 0 :(得分:3)
也可以使用UIImage,但我更喜欢UIButton以防需要点击。由于UIImageView直接继承自UIView,因此它并不真正了解目标和选择器。
UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
imageButton.frame = CGRectMake(x,y,width,height
[imageButton setBackgroundImage:[UIImage imageNamed:
[NSString stringWithFormat:@"image%02ds.jpg", i+1]] forState:UIControlStateNormal];
[imageButton addTarget:self action:@selector(imageButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
-(void)imageButtonTapped:(id) sender
{
//Do whatever you want to do on image tap.
}
答案 1 :(得分:1)
我建议使用GMGridView,而不是创建自己的GridView http://www.cocoacontrols.com/controls/gmgridview
这是一个很好的控件,可以处理所有点击和所有内容 - 您只需要实现委托方法并按照示例操作。我以前用过它,效果很好;委托/数据源方法与UITableView非常相似,所以起初不会太混乱。
如果您不想包含外部课程,那么我建议您执行MSK所说的内容 -
答案 2 :(得分:1)
您可以将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
}
}
}