简体   繁体   English

从xib加载自定义UIView

[英]Loading a custom UIView from xib

I have a custom UIView which I am loading in this manner 我有一个自定义UIView ,我以这种方式加载

- (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 . 在UIView方法返回self时加载这样的视图时, Interface Builder中链接的所有出口都是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. 据我所知,您在xid中提供IBOutlet,当您尝试加载视图时,您提供的这些值为零。 This is anticipated becouse you create onew viwe and add the view from xib as subview. 这是预期的,因为您创建onew viwe并将xib中的视图添加为子视图。 So the parrent view does not set this values. 所以parrent视图没有设置这个值。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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