2013-02-19 22 views
2

我使用CustomView.xib文件创建了CustomView:UIView。 现在我想通过拖动视图到另一个XIB(例如:UIViewController.xib)并选择class:customView来使用它。在另一个XIB中指定类时如何使用CustomView.xib加载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; 
} 

在这种情况下通过绘制到另一个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; 
} 
+0

没有得到你..你想要什么? – 2013-02-19 09:57:21

+0

我想加载CustomView和它的xib,但不使用initWithFrame,只需将视图拖到另一个Xib,然后指定class.But不加载XIB。 – 2013-02-19 10:01:50

+0

我想这是你想要做的,不是吗? http://stackoverflow.com/a/5096476/840428 – followben 2013-02-19 10:12:50

回答

1

直接拖动定制厦门国际银行在您的视图控制器不possible.But你可以做一两件事,拖动其超类视图和它的类设置为自定义class.And它的属性连接到将要放置的对象根据您的自定义类。

您可以直接加载自定义的厦门国际银行使用下面的代码:

//负荷厦门国际银行使用代码....

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; 
    } 
} 

[email protected]"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]; 
     [email protected]"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