问题
I've created a custom view that loads its content from a nib, like this:
/* PricingDataView.h */
#import <UIKit/UIKIt.h>
@interface PricingDataView : UIView {
UIView *contentView;
}
@property (nonatomic, retain) IBOutlet UIView *contentView;
@end
/* PricingDataView.m */
#import "PricingDataView.h"
@implementation PricingDataView
@synthesize contentView;
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[[NSBundle mainBundle] loadNibNamed:@"PricingDataView" owner:self options:nil];
[contentView setFrame:frame];
[self addSubview:contentView];
}
return self;
}
/* ... */
In the nib file I set PricingDataView
as the type of the File's Owner, and connected the contentView
outlet in IB. I placed a regular UIView
from the Interface Library onto the full-sized view shown to the user, and then changed it's class name to PricingDataView
. It all builds, but at runtime, nothing is rendered where my custom view is supposed to be.
I put breakpoints in PricingDataView.initWithFrame
, but they don't hit, so I know I'm missing something that would cause the view to be initialized. What I'm curious about is that in the process of loading my other views from nibs, all the initialization happens for me, but not with this one. Why?
回答1:
Are you sure your other views aren't using a UIViewController
? Here's a quote from the documentation for initWithFrame:
from UIView
:
If you use Interface Builder to design your interface, this method is not called when your view objects are subsequently loaded from the nib file. Objects in a nib file are reconstituted and then initialized using their initWithCoder: method, which modifies the attributes of the view to match the attributes stored in the nib file. For detailed information about how views are loaded from a nib file, see Resource Programming Guide.
回答2:
when you add files in Interface Builder at runtime it calls the
-(id)initWithCoder:(NSCoder *)aDecoder
and not the initWithFrame.
回答3:
just Undo the class name (PricingDataView
) of the view that you add to UIView
. In this case the initWithFrame
: method would be called.
previously awakeFromNib
was called in loop. As your customView
and the View
you are adding via Nib
as a subView
are of the same class type.
来源:https://stackoverflow.com/questions/2769210/custom-view-with-nib-as-subview-doesnt-seem-to-be-loading