在界面构建器中添加的自定义UIView不会加载xib

 手机用户2502898521 发布于 2023-02-13 16:25

UIView用xib 创建了自定义.

另外我UIViewController在我的故事板中有一个,我添加了一个UIView并将其类设置为我的自定义UIView.

但是当我运行应用程序时,视图没有其子视图.调试时,所有子视图都为null.

在自定义的.m中UIView,存在以下init方法:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {

    }
    return self;
}

我错过了什么?

1 个回答
  • 正如您所知,UIViewController我们有-initWithNibName:bundle:一种方法可以将它与xib连接起来.
    但是......
    当涉及到a时UIView,你需要使用-loadNibNamed:owner:options:xib 来加载它.(只是在xib中为视图指定自定义类将不起作用)


    假设:

      创建了一个UIView名为的子类CustomXIBView

      (新文件> Cocoa Touch> Objective-C类 - 子类UIView)

      创建了一个简单的视图用户界面并命名它 CustomXIBView

      (新文件>用户界面>查看)

    脚步:

      转到CustomXIBView笔尖

      选择View(左侧工具栏)

      选择Show Identity Inspector(右侧面板中的第3个选项)

      指定CustomXIBView作为自定义类View

      不要做任何CustomXIBViewFile's Owner在笔尖

      拖放对象并将其连接 CustomXIBView.h

    码:

    //To load `CustomXIBView` from any `UIViewController` or other class: 
    //instead of the following commented code, do the uncommented code
    //CustomXIBView *myCustomXIBViewObj = [CustomXIBView alloc] init];
    //[myCustomXIBViewObj setFrame:CGRectMake(0,0,320,480)];
    
    //Do this:
    CustomXIBView *myCustomXIBViewObj = 
         [[[NSBundle mainBundle] loadNibNamed:@"someView"
                                        owner:self
                                      options:nil]
                                objectAtIndex:0];
    [myCustomXIBViewObj setFrame:CGRect(0, 
                                        0, 
                                        myCustomXIBViewObj.frame.size.width, 
                                        myCustomXIBViewObj.frame.size.height)];
    [self.view addSubview:myCustomXIBViewObj];
    

    参考:http://eppz.eu/blog/uiview-from-xib/

    2023-02-13 16:26 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有