UIView和XIB连接.显示它

UIView and XIB connections.Displaying it?

本文关键字:显示 连接 XIB UIView      更新时间:2023-10-16

如何在UIView上显示XIB/NIB文件?我找过了,但没找到这个。我想在主视图上显示xib接口,我有五个xib文件,我需要在UIView上显示每个xib文件!有些人说这段代码是代码,但我要实现的是:

NSArray *screens=[[NSBundle mainBundle] loadNibNamed:@"JaneiroClass" owner:self options:nil];          
        [self addSubview:[screens objectAtIndex:0]];

这将从XIB加载视图。UINib还可以缓存,因此您可以快速删除它们。

UINib *nib = [UINib nibWithNibName:@"TestView" bundle:nil];
UIView *myView = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0]];

instantiateWithOwner返回XIB中顶层对象的数组。在上面的例子中,只有一个视图(上面有库中的其他对象),所以我们检索objectAtIndex:0.

一旦有了视图,就可以将其添加到其他视图中。例如,你可以在另一个视图上调用addSubView,传递这个:

[someView addSubView:myView];

我在我的博客http://effectivemobility.blogspot.com/2011/05/using-custom-cells-in-your-uitableview.html上发表了一篇关于从nib加载自定义视图的文章

关键部分是这个方法

+ (id)customViewForClass:(Class)customClass {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(customClass) owner:nil options:nil];
    for ( id currentObject in topLevelObjects ) {
        if ( [currentObject isKindOfClass:customClass] ) {
            return currentObject;
        }
    }
    return nil;
}