Cocoa application duplicated view

I have a Cocoa application and I'm trying to set up an NSImageView without using story board (using storyboard works just fine tho).

Also, I'm kinda new to Cocoa so any advice is appreciated.

Anyway so here's the deal, I created a class to encapsulate this image:

@interface MyView : NSView
{
@private
    NSImageView* imageView;
}
@end 
@implementation MyView

-(id) initWithFrame:(NSRect)frameRect
{
    self = [super initWithFrame:frameRect];
    
    if(self)
    {
        NSRect rect = NSMakeRect(10, 10, 100, 200);
        imageView = [[NSImageView alloc] initWithFrame:rect];
        NSImage* image = [NSImage imageNamed:@"bob.jpeg"];
        [imageView setImageScaling:NSImageScaleNone];
        [imageView setImage: image];
        [self addSubview: imageView];
    }
    
    return self;
}

-(id) init
{
    return [self initWithFrame:NSMakeRect(10, 10, 100, 100)];
}

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];
    
    // Drawing code here.
}

@end

Now, in the view controller file, in the viewDidLoad I tried to load add this as a subview to get it to display my image:

- (void)viewDidLoad
{
    [super viewDidLoad];
        
    MyView *customView = [[MyView alloc] init];
    
    [self.view addSubview:customView];
    
}

This kinda works, except that it loads the image twice, I ended up with two images instead of just one like I intended, what gives? what am I doing wrong here?

Answered by Claude31 in 806876022

Welcome to the forum.

If I understand, you create the imageView a first time by

    MyView *customView = [[MyView alloc] init];

as init calls initWithFrame which itself adds the imageView

and a second time with

    [self.view addSubview:customView];

Try removing this second one. Does it work ?

Accepted Answer

Welcome to the forum.

If I understand, you create the imageView a first time by

    MyView *customView = [[MyView alloc] init];

as init calls initWithFrame which itself adds the imageView

and a second time with

    [self.view addSubview:customView];

Try removing this second one. Does it work ?

Cocoa application duplicated view
 
 
Q