Question

In myViewController.m I'm trying to add as subview a custom UIView called AlbumView :

-(void)viewDidLoad {

 AlbumView *album = [[AlbumView alloc]init];

 [self.view addSubView:album];

 NSLog(@"album-frame: %@",NSStringFromCGRect(album.frame));

}

The NSLog is printing : album-frame:{{0, 0}, {0, 0}}

Since the AlbumView class has the following Xib and I can still see it correctly sized when I build and run my app, even if I didn't use any initWithFrame: method to initialize it. So I was wondering:

-Why couldn't I access its correct frame size when NSLogging in viewDidLoad (or viewDidAppear)?

enter image description here

EDIT: The following is The Xib class - AlbumView.m

-(void)setupView{

    [[NSBundle mainBundle] loadNibNamed:@"AlbumView" owner:self options:nil];
    [self addSubview:self.view]; //where self.view is IBOutlet connected with the actual Xib view I posted above 


}

-(id)initWithFrame:(CGRect)frame{
    if((self = [super initWithFrame:frame])){
        [self setupView];
    }

    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    if((self = [super initWithCoder:aDecoder])){
        [self setupView];
    }

    return self;
}


- (void) awakeFromNib
{
    [super awakeFromNib];

    [self addSubview:self.view];
}
Was it helpful?

Solution

You're initializing AlbumView by sending it the init message, which is equivalent to sending it initWithFrame:CGRectZero. Then, after you load the nib, you're not doing anything to change your frame to match the contents of the xib. Try this:

-(void)setupView{
    [[NSBundle mainBundle] loadNibNamed:@"AlbumView" owner:self options:nil];

    // Make my frame size match the size of the content view in the xib.
    CGRect newFrame = self.frame;
    newFrame.size = self.view.frame.size;
    self.frame = newFrame;

    [self addSubview:self.view]; //where self.view is IBOutlet connected with the actual Xib view I posted above 
}

OTHER TIPS

// AlbumView.h

+ (instancetype)getView;

// AlbumView.m

+ (instancetype)getView {
    return [[[UINib nibWithNibName:@"AlbumView" bundle:nil] instantiateWithOwner:self options:nil] lastObject];
}

// myViewController.m

...

- (void)viewDidLoad {

 AlbumView *album = [AlbumView getView];

 [self.view addSubView:album];

 NSLog(@"album-frame: %@",NSStringFromCGRect(album.frame));

}

...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top