OGeek|极客世界-中国程序员成长平台

标题: ios - 在另一个 XIB 中指定类时如何使用 Custom View.xib 加载自定义 View ? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 08:52
标题: ios - 在另一个 XIB 中指定类时如何使用 Custom View.xib 加载自定义 View ?

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

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

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

//自定义 View .m

- (id)initWithFrameCGRect)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)initWithCoderNSCoder *)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;
}



Best Answer-推荐答案


在您的 View Controller 中直接拖动自定义 xib 是不可能的。但是您可以做一件事,拖动其父类(super class) View 并将其类设置为您的自定义类。并将其属性连接到您将根据您的自定义放置的对象类。

您可以使用以下代码直接加载您的自定义 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

关于ios - 在另一个 XIB 中指定类时如何使用 Custom View.xib 加载自定义 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14954523/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4