简体   繁体   中英

Loading a custom UIView from xib

I have a custom UIView which I am loading in this manner

- (id)initWithFrame:(CGRect)frame withDelegate:(id)del
{
    self = [super initWithFrame:frame];
    UIView *myView;

    if (self)
    {
        NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
                                                      owner:self
                                                    options:nil];
        for (id object in nibViews) 
        {
            if ([object isKindOfClass:[self class]])
            myView = object;
        }

        myView.frame = frame;
        myView.backgroundColor = [UIColor clearColor];

        [self addSubview: myView];
    }

    self.delegate = del;
    return self;
}

On loading the view like this when UIView method returns self all the outlets linked in the Interface Builder are nil . Is it not the right way ?

使用此方法从bundle加载特定的xib

UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];

Try this :

 self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
                                              owner:self
                                            options:nil] objectAtIndex:0];

Use this

myView =[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil].firstObject];

Or simple you can use

myView = [nibViews firstObject]

As I understand you provide IBOutlet in the xid and when you try to load the view like you provide these values is nil. This is anticipated becouse you create onew viwe and add the view from xib as subview. So the parrent view does not set this values. to fixe this you need to rework method as loaded your view. Please try use this:

+ (id)createWithFrame:(CGRect)frame withDelegate:(id)del
{


    NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class])
                                                      owner:nil
                                                    options:nil];
    <Provide class name> *myView = nibViews[0];
    myView.frame = frame;
    myView.backgroundColor = [UIColor clearColor];

    myView.delegate = del;
    return myView;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM