How can I change the image displayed in a UIImageView programmatically?

后端 未结 15 636
孤街浪徒
孤街浪徒 2020-12-07 08:42

I have an IBOutlet to a UIImageView, but when I look at the UIImageView doc, I can\'t see any hints about programmatically changing it

相关标签:
15条回答
  • 2020-12-07 09:28

    If you have an IBOutlet to a UIImageView already, then all you have to do is grab an image and call setImage on the receiver (UIImageView). Two examples of grabbing an image are below. One from the Web, and one you add to your Resources folder in Xcode.

    UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
    

    or

    UIImage *image = [UIImage imageNamed: @"cell.png"];
    

    Once you have an Image you can then set UIImageView:

    [imageView setImage:image];
    

    The line above assumes imageView is your IBOutlet.

    That's it! If you want to get fancy you can add the image to an UIView and then add transitions.

    P.S. Memory management not included.

    0 讨论(0)
  • 2020-12-07 09:28

    My problem was that I tried to change the image in an other thread. I did like this:

    - (void)changeImage {
        backgroundImage.image = [UIImage imageNamed:@"img.png"];
    }
    

    Call with:

    [self performSelectorOnMainThread : @selector(changeImage) withObject:nil waitUntilDone:NO];
    
    0 讨论(0)
  • 2020-12-07 09:29

    This worked for me

    [ImageViewName setImage:[UIImage imageNamed: @"ImageName.png"]];
    

    Make sure that the ImageView is declared properly in the .h file and is linked with the IB element.

    0 讨论(0)
提交回复
热议问题