Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS: change UIImageView with tag value

I have 20 UIImageView and i want change their image; but I don't want to create 20 IBOutlet, and I want to use tag value to change the image; I set the tag value in interface builder and after? If I want to change image at Imageview number 15? How can I do?

like image 238
cyclingIsBetter Avatar asked Apr 29 '11 09:04

cyclingIsBetter


3 Answers

UIImageView *imageView=(UIImageView *)[self.view viewWithTag:*givetag*];
[imageView setImage:[UIImage imageNamed:@"nameof yourimage"]];
like image 132
Gypsa Avatar answered Nov 19 '22 15:11

Gypsa


If you use tags you can identify your tagged view (UIImageView is a subclass of UIView, which has the tag attribute) like this:

- (UIView *)viewWithTag:(NSInteger)tag

So if you call this method on your superview (which all the UIImageViews reside in), you should do it like this:

UIImageView *myImageView = (UIImageView *)[myAwesomeSuperview viewWithTag:15];

(Documentation I found using Google).

P.S: if you think it is too much work to add 20 IBOutlets, I recommend you create the UIImageViews programmatically as well. This way you will not need a xib file at all, write a small piece of code and have better maintenance with less effort.

like image 43
Jake Avatar answered Nov 19 '22 16:11

Jake


SWIFT, April 2015:

func createUIImageViews()
{
    for i in 0...99
    {
        var imageView:UIImageView = UIImageView(frame: CGRectMake(CGFloat(0), CGFloat(0), CGFloat(100), CGFloat(100)))
        imageView.userInteractionEnabled = true
        imageView.tag = i
        imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "onImageViewTap:"))

        self.view.addSubview(imageView)
    }
}



func onImageViewTap(sender:UITapGestureRecognizer)
{
    println("TAP: \(sender.view!.tag)")
}
like image 2
Thyselius Avatar answered Nov 19 '22 15:11

Thyselius