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

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 に答える
1

独自のGridViewを作成する代わりに、GMGridViewhttp ://www.cocoacontrols.com/controls/gmgridviewを使用することをお勧めします

これは、すべてのクリックとすでにすべてを処理する優れたコントロールです。デリゲートメソッドを実装し、例に従うだけです。私は以前にそれを使用して素晴らしい結果を出しました。デリゲート/データソースメソッドはUITableViewに非常に似ているため、最初はそれほど混乱しません。

外部クラスを含めたくない場合は、MSKが言ったことを実行することをお勧めします-

于 2012-12-21T18:58:20.093 に答える