Adding an Image in Xcode 4.5

Discussion in 'Mac Programming' started by Blakeasd, Dec 14, 2012.

  1. macrumors 6502a

    Dec 29, 2009

    This is my first time writing/updating an application since ~ the beta version of OS X Lion. I am trying to add an image to an NSView in interface building. Here are the steps that I followed:

    1. Dragged images to Xcode "Supporting Files" Group (Copy was checked)
    2. Went to the interface building section, pressed on the media tab and dragged the image to the NSView

    Presses the Run button and... got an error stating that Xcode "Could not find the imaged named" [image name]

    What has changed that won't allow me to add an image? I noticed a similar thing with adding new classes, I have to target the .m file in the inspector or Xcode cannot find it. The image under the inspector is check under the "Target Membership" table in the inspector. Could someone please help me?

  2. macrumors regular

    Jun 29, 2010
    The Netherlands
    What you need to do is the following:

    1. Make a new subclass of NSView.
    2. Add an NSImageView instance variable to it. (You know, in the newly made .h file)
    3. Initialize the NSImageView in the init method of your NSView subclass, you know, the .m file.

    It will look something like this:
    //  MyImageView.m
    #import "MyImageView.h"
    @implementation ImageView
    - (id)initWithFrame:(NSRect)frame
        self = [super initWithFrame:frame];
        if (self) {
            theImage = [[NSImage alloc] initWithContentsOfFile:@"Your Image"];
            theImageView = [[NSImageView alloc] initWithFrame:[self bounds]];   //Doesn't necessarily have to be this value 
            [theImageView setImageScaling:NSScaleToFit]; // Same goes for this one
            [theImageView setImage:theImage];
            [self addSubview:theImageView];
        return self;
    - (void)drawRect:(NSRect)dirtyRect {
        // Add drawing code, if necessary. (Don't think it is for you)
    3. Now, in Interface Builder select your custom view for your image.
    4. Select the Identity Inspector, and set it's class to "MyImageView" (or whatever name you gave it)
    5. Build and Run your project.

    Feel free to ask more, if needed. :)
  3. thread starter macrumors 6502a

    Dec 29, 2009

Share This Page