0

我只想在 viewcontoller 的 xib 或 stroy 板上加载自定义视图(使用 xib)。这样做的最佳做法是什么。

我在下面使用了 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;
}

但在使用此功能后,我的 awakeFromNib 开始多次调用。

请建议。

4

1 回答 1

0

正如您所发现的,当前链接到的正确答案过于复杂和错误。有一个更标准和更好的方法来做到这一点:

  1. 创建一个空的 XIB
  2. 将 UIView 添加到您的 XIB,使其成为唯一的顶级对象(除了代理 First Responder 和 File's Owner)
  3. 将新 UIView 的类更改为 CustomView
  4. 实例化 XIB 并检索您的 CustomView 实例,如下所示:

    CustomView *view = [[UINib nibWithNibName:@"CustomView" bundle:nil] instantiateWithOwner:self options:nil][0];

  5. 在视图控制器的 viewDidLoad 方法中将其添加到视图层次结构中:

    [self.view addSubview:view];

-initWithCoder:如果您需要进行任何自定义初始化,请务必在您的 CustomView 子类中覆盖。我知道这很多,所以如果这些步骤让您感到困惑或遇到困难,请告诉我。

于 2013-08-04T01:51:37.393 回答