2

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

当我初始化CustomView并将SubView添加到另一个视图时,我可以成功加载:

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

//自定义视图.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 中来重用 CustomCell,然后将类指定为 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;
}
4

1 回答 1

1

Directly drag custom xib in your view controller is not possible.But you can do one thing,drag its super class view and set its class to your custom class.And connect its properties to the objects you will place according to your Custom Class.

You can directly load your custom xib using following code:

//load xib using code ....

   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.

Here is a working code TestTouchonView

And the Screenshot will display as follows.

enter image description here

于 2013-02-22T05:16:19.303 回答