在iOS中以编程方式将图像设置为imageView

时间:2013-12-09 21:48:52

标签: ios imageview

我正在开发一个iOS应用程序,我有一个for循环来创建图像。 当图像接收到点击时,我想更改图像的背景,仅更改为该图像。我怎么能这样做?

这是我的代码:

for (int i =0; i<dim; i++) {

likeImageImageview = [[UIImageView alloc] initWithFrame:CGRectMake(paddWidth*20,7.5,39.6,39.6)];

    img0 = [UIImage imageNamed:@"like"];
    [likeImageImageview setImage:img0];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImagesLike)];
    singleTap.numberOfTapsRequired = 1;                                                                                                 
    likeImageImageview.userInteractionEnabled = YES;                                                                                            //l'utente può cliccare
    [likeImageImageview setMultipleTouchEnabled:NO];                                                                                            //non è consentito il multitouch
    [likeImageImageview addGestureRecognizer:singleTap];

[row_like addSubview:likeImageImageview];

}

这是方法:

-(void)tapImagesLike{               

 likeImageImageview.image = [UIImage imageNamed:@"mylike"];

}

使用此代码,只有最后一个imageview更改其背景。我怎样才能像ID一样使用“i”?

2 个答案:

答案 0 :(得分:0)

for loop

UIImageView *imageView = …

imageView.tag = i;

所以你需要获得被挖掘的视图

- (void)tapImagesLike:(UITapGestureRecognizer*)recognizer
{
    UIImageView *imageView = (UIImageView*)recognizer.view;
    int i = imageView.tag;
    // Then you can do the change you need to do here
}

这是在手势识别器点击发生时应该调用的方法。

答案 1 :(得分:0)

它只显示最后一张图像,因为您正在for循环中创建一个新实例。

试试这个

NSMutableArray *tempImageArray=[[NSMutableArray alloc]init];
for (int i =0; i<10; i++) {

   UIImageView *likeImageImageview = [[UIImageView alloc] initWithFrame:CGRectMake(20,7.5,39.6,39.6)];

   UIImage *img0 = [UIImage imageNamed:@"like"];
    [likeImageImageview setImage:img0];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImagesLike:)];
    singleTap.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:singleTap];
    [row_like addSubview:likeImageImageview];
    [tempImageArray addObject:likeImageImageview];
}
self.imageArray=tempImageArray;
[tempImageArray release];

并且

- (void)tapImagesLike:(UITapGestureRecognizer*)recognizer{
     UIImageView *imageView = (UIImageView *)[self.imageArray objectAtIndex:0];
     imageView.image=[UIImage imageNamed:@"0.png"];  
}