简体   繁体   English

如何在xib或情节提要上使用xib加载自定义视图

[英]how to load custom view with xib on a xib or storyboard

I just want to load a custom view (with xib) on a viewcontoller's xib or stroy board.What is the best practice to do the same. 我只想在viewcontoller的xib或装饰板上加载自定义视图(使用xib)。最佳做法是这样做

I have used awakeAfterUsingCoder function code below. 我在下面使用了awakeAfterUsingCoder函数代码。

(id) awakeAfterUsingCoder:(NSCoder*)aDecoder
{
    BOOL theThingThatGotLoadedWasJustAPlaceholder = ([[self subviews] count] == 0);
    if (theThingThatGotLoadedWasJustAPlaceholder)
    {
        CustomView* theRealThing = (id) [CustomView view];
        theRealThing.frame = self.frame;
        theRealThing.autoresizingMask = self.autoresizingMask;
        return theRealThing;
    }
    return self;
}

but after using this function my awakeFromNib started calling multiple time. 但是使用此功能后,我的awakeFromNib开始多次调用。

Please sugegst. 请萨格斯特。

The correct answer currently linked to is overly complicated and buggy, as you have found out. 如您所知,当前链接到的正确答案过于复杂和错误。 There is a much more standard and better way to do this: 有一种更标准,更好的方法来执行此操作:

  1. Create an empty XIB 创建一个空的XIB
  2. Add a UIView to your XIB so that it is the only top-level object (aside from the proxies First Responder and File's Owner) 将UIView添加到您的XIB,使其成为唯一的顶级对象(除了代理First Responder和File的所有者之外)
  3. Change the class of your new UIView to CustomView 将新的UIView的类更改为CustomView
  4. Instantiate the XIB and retrieve your CustomView instance like so: 实例化XIB并检索您的CustomView实例,如下所示:

    CustomView *view = [[UINib nibWithNibName:@"CustomView" bundle:nil] instantiateWithOwner:self options:nil][0]; CustomView * view = [[[UINib nibWithNibName:@“ CustomView”捆绑包:无] instantiateWithOwner:self选项:无] [0];

  5. Add it to your view hierarchy in your view controller's viewDidLoad method: 通过视图控制器的viewDidLoad方法将其添加到视图层次结构中:

    [self.view addSubview:view]; [self.view addSubview:view];

Be sure to override -initWithCoder: in your CustomView subclass in case you need to do any custom initialization. 一定要重写-initWithCoder:在情况下,你CustomView子类,你需要做的任何定制的初始化。 I know this is a lot, so please let me know of any if these steps confuse you or if you get stuck. 我知道很多事情,所以如果这些步骤使您感到困惑或卡住,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM