0

我有一个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];


}
4

3 回答 3

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.      
    }
于 2012-12-21T18:58:56.380 回答
1

我建议不要创建自己的 GridView,而是使用 GMGridView http://www.cocoacontrols.com/controls/gmgridview

它是一个很好的控件,可以处理所有的点击和一切——您只需要实现委托方法并按照示例进行操作。我以前用过,效果很好;委托/数据源方法与 UITableView 非常相似,因此一开始并不会太混乱。

如果您不想包含外部课程,那么我建议您按照MSK所说的进行 -

于 2012-12-21T18:58:20.093 回答
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
        }
    }
}
于 2012-12-21T19:04:36.657 回答