Wednesday, 5 June 2013

How to change the image inside UIImageView programmatically: Xcode


In this tutorial, you are going to study how to change the images inside an UIImageView in button click.




 For that, first drag & drop 2 images(say Image1.png & Image2.png)to the project

in.h:

    @interface ViewController : UIViewController
    {
        IBOutlet UIImageView *imageView_;
    }
    -(IBAction)changeToimg1;
    -(IBAction)changeToimg2;
    @end

   
in.m:

    @implementation ViewController

    -(IBAction)changeToimg1
    {
        // This will set Image1.png as the UIImageView image
        UIImage *img1 = [UIImage imageNamed:@"Image1.png"];
        [imageView_ setImage:img1];
    }

    -(IBAction)changeToimg2
    {
        // This will set Image2.png as the UIImageView image
        UIImage *img2 = [UIImage imageNamed:@"Image2.png"];
        [imageView_ setImage:img2];
    }

   
in.xib:
  • Drag and drop UIImageView to the main window
  • Place 2 UIButtons on the screen, name the button labels as Image1 and Image2 respectively for your conveniance
  • Click on the imageView and co
               New Referencing Outlet   --->    imageView_
  • Click on Button1 and connect
               Touch Up Inside             ---->    changeToimg1
  •  Click on Button2 and connect   
               Touch Up Inside          ---->   changeToimg2



Now save and Run the program. Click on the buttons, and you can see the images changing.

No comments:

Post a Comment