Reputation: 44973
I have these two pieces of code. The first one works perfectly:
UIView *tmp = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 60.0f, 296.0f, 44.0f)];
[self.dynamicView addSubview:tmp];
[tmp release];
The second one is pretty much the same, but the view doesn't show up.
CommentBox *commentBox = [[CommentBox alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 296.0f, 44.0f)];
[self.dynamicView addSubview:commentBox];
[commentBox release]; // Why does this remove the view?
If I remove the [commentBox release]
the view surprisingly appears. But I don't see a different between these two code snippets.
The init for the CommentBox looks like this:
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
// Load the nib:
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CommentBox" owner:self options:nil];
self = [nibObjects objectAtIndex:0];
}
return self;
}
Upvotes: 0
Views: 621
Reputation: 44973
After thinking about Graham's answer I came up with the following solution:
In the code I do now the following within my -initWithFrame:
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CommentBox" owner:self options:nil]; UIView *subView = [[nibObjects objectAtIndex:0] viewWithTag:300]; [self addSubview:subView];
Hope that helps.
Update:
I just had another idea of doing it. Instead of the tag numbers you can also create a IBOutlet UIView *viewHolder
in the CommentBox
class and set the outlet in IB. Then in the initWithFrame:
I do the following:
[[NSBundle mainBundle] loadNibNamed:@"CommentBox" owner:self options:nil];
[self addSubview:self.viewHolder];
Upvotes: 3
Reputation:
You're doing weird things in -initWithFrame:
. I'm not 100% sure that it's causing the problem you report, but I'm pretty sure it's:
I don't think replacing a view object with something dearchived from a nib in its -init…
methods is a good idea. Either load the nib from a controller class, or have your initialiser load the object's subviews from the nib without replacing self
.
Upvotes: 2