I ended up using the steps in the last edited here , and they worked just fine.
You are using a regular UIView as the top level view in xib .
Then you set the owner of the file to a custom subclass ( CustomView ).
Finally, you add the line:
[self addSubview:[[[UINib nibWithNibName:@"CustomView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0]];
in the if (self != nil) block in both initWithCoder and initWithFrame .
Voila! IBOutlets connected and ready to work after a call. Really happy with the solution, but it was very difficult to dig out.
Hope this helps anyone.
EDIT : I updated the link to the one that is not dead. Since I never registered the full code, here is what it looks after modification:
- (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { UIView *nib = [[[UINib nibWithNibName:@"CustomView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0]; [self addSubview:nib]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { UIView *nib = [[[UINib nibWithNibName:@"CustomView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0]; [self addSubview:nib]; } return self; } - (void)awakeFromNib { [super awakeFromNib]; [self setup]; } - (void)setup {
This pattern has become so common that I actually created a category on UIView called UIView+Nib that implements the following method:
+ (UIView *)viewWithNibName:(NSString *)nibName owner:(id)owner { return [[[UINib nibWithNibName:nibName bundle:nil] instantiateWithOwner:owner options:nil] objectAtIndex:0]; }
Thus, the above code can be simplified to:
[self addSubview:[UIView viewWithNibName:@"CustomView" owner:self]];
Note also that the code above can be reorganized even more, since the logic is exactly the same in initWithFrame: and initWithCoder: Hope this helps!
Dr. Acula
source share