簡體   English   中英

從xib加載自定義UIView

[英]Loading a custom UIView from xib

我有一個自定義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;
}

在UIView方法返回self時加載這樣的視圖時, Interface Builder中鏈接的所有出口都是nil 這不是正確的方法嗎?

使用此方法從bundle加載特定的xib

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

嘗試這個 :

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

用這個

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

或者你可以使用簡單

myView = [nibViews firstObject]

據我所知,您在xid中提供IBOutlet,當您嘗試加載視圖時,您提供的這些值為零。 這是預期的,因為您創建onew viwe並將xib中的視圖添加為子視圖。 所以parrent視圖沒有設置這個值。 要解決這個問題,你需要在加載視圖時重做方法。 請嘗試使用此:

+ (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