Marci-man
Marci-man

Reputation: 2233

NSImageView setImage won't set image

I am trying to set image for an NSImageView instance object in a Cocoa project. My code looks like this:

itemTableCellView * xx = [tableView makeViewWithIdentifier:@"MainCell" owner:self];
    xx.label.stringValue = [tempCi simpleTxt];
    xx.img = [[NSImageView alloc]initWithFrame:CGRectMake(48, 48, 48, 48)]];
    NSImage * localimage = [NSImage imageNamed:@"menubar icon"];
    [xx.img setImage:localImage];
    return  xx;

The variable imgis of type NSImageView. The variable localImage loads the correct image, I have checked it in the log. The variable lable is initialized correctly and gets the right value

I just keep on getting empty NSImageViews in my app.

Upvotes: 0

Views: 1785

Answers (4)

Emmanuel
Emmanuel

Reputation: 2917

Your NSImageView is initialized with no size (it's frame equals NSZeroRect), also you don't add the image view to any subview.

Upvotes: 3

Marci-man
Marci-man

Reputation: 2233

Well, yet another quirk of Objective-C!

I found out that even when a NSImageView is a property of an NSView, it needs to be added to it through:

[xx addSubview:xx.img];   

Well, played Cocoa, very well played!
cheers!

Upvotes: 1

AlieN
AlieN

Reputation: 543

You should use

xx.img = [[NSImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];

Or, maybe, as img is property, you don't need to init it at all? And just use

xx.img.frame=CGRectMake(x, y, width, height);

Upvotes: 1

user3339357
user3339357

Reputation: 292

when you create your NSimageView,try doing an initwithframe:. This will set a size for the NSImageView. I believe that you might be drawing in a rect of size zero otherwise.

Upvotes: 1

Related Questions