如何在另一个XIB中指定类时,如何使用自定义View.xib加载自定义视图?

时间:2013-02-19 09:51:38

标签: ios uiview uinib

我使用CustomView.xib文件创建CustomView:UIView。 现在我想通过拖动视图将其用于另一个XIB(例如:UIViewController.xib)并选择class:customView。

当我将CustomView和addSubView初始化为anotherView时,我可以加载成功:

- (void)viewDidLoad{
    //Success load NIB
    CustomView *aView = [[CustomView alloc] initWithFrame:CGRectMake(40, 250, 100, 100)];
    [self.view addSubview:aView];
}

// CustomView.m

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        NSLog(@"INIT");
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        [[nib objectAtIndex:0] setFrame:frame];
        self = [nib objectAtIndex:0];
    }
    return self;
}

在重用CustomCell的情况下,将其绘制到另一个XIB中,然后将类指定为CustomView。我知道awakeFromNib被调用但不知道如何加载CustomView.xib。 怎么做?

*编辑:

在指定类时也会调用initWithCoder,但它会使用loadNibNamed创建一个循环并崩溃。为什么?

- (id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        NSLog(@"Coder");
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"QSKey" owner:nil options:nil];
        [[nib objectAtIndex:0] setFrame:self.bounds];
        self = [nib objectAtIndex:0];
    }
    return self;
}

1 个答案:

答案 0 :(得分:1)

直接在视图控制器中拖动自定义xib是不可能的。但是你可以做一件事,拖动它的超类视图并将它的类设置为你的自定义类。并根据你的自定义将它的属性连接到你将放置的对象类。

您可以使用以下代码直接加载自定义xib:

//使用代码加载xib ....

   QSKey *keyView=[[QSKey alloc] init];
   NSArray *topObjects=[[NSBundle mainBundle] loadNibNamed:@"QSKey" owner:self options:nil];

for (id view in topObjects) {
    if ([view isKindOfClass:[QSKey class]]) {
        keyView=(QSKey*)view;
    }
}

keyView.label.text=@"CView";
[keyView setFrame:CGRectMake(0, 0, 100, 100)];
[keyView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:keyView];

here label is UILabel object you have used in your custom class as its property.


//Load custom View using drag down objects of type Custom Class Super class.

for (QSKey *aView in self.view.subviews) {
    if ([aView isKindOfClass:[QSKey class]]) {
        [self addGestureRecognizersToPiece:aView];
        aView.label.text=@"whatever!";
    }
}

Here label is object of UILabel you have to place on your dragged View to view controller's xib view.Change that view's class to your Custom Class.Then it will will show its label property in outlet connect it to your UILabel object placed over dragged view.

这是一个有效的代码TestTouchonView

屏幕截图将显示如下。

enter image description here