单击选项卡时,选项卡栏控制器不显示 XIB UIViewController

Tab Bar Controller does not display XIB UIViewController when tab is clicked

场景如下

创建新项目选项卡式应用程序。使用 XIB 文件添加新控制器,TestViewController,在 XIB 文件中只需添加一个带有文本 "TestViewControllerButton".

的按钮

如果我在 FirstViewController 中创建一个按钮,并添加一个动作以转到 TestViewController,则显示 XIB 文件中的按钮。

TestViewController* vc = [[TestViewController alloc] init];
[self presentViewController:vc animated:YES completion:nil];

问题是当我将 TestViewController 添加到选项卡控制器(索引 2,从 0 开始)时,它不显示 XIB(我的意思是,按钮不显示)。

这是我的步骤。我在 Tab Controller 中添加 UIViewController,然后在 Identity Inspector 中将 class 更改为 TestViewController。然后将 Tab Bar Item 添加到 TestViewController 并将其 link 添加到 Tab Bar Controller,因此当单击最后一个选项卡时,它 linked 到 TestViewController。但是问题是,XIB中的按钮没有显示(我在TestViewController.xib中添加了按钮)。

是的,当然我可以直接在我的测试Main.storyboard中添加按钮ViewController,但我的想法是我想在测试ViewController中管理UI ] XIB,main.storyboard 只是在 TestViewController 图像中加载视图。

好的,我添加一些屏幕截图来理解。当我以编程方式执行此屏幕 运行 时,运行 in UIViewController(上面的代码 - self presentViewController:vc animated:YES completion:nil ).

当我从 Tab运行

我认为设置已经正确(因为运行在UIViewController中很好)

已将文件所有者设置为测试ViewController

已绑定插座

谢谢!

我认为您使用的是 ViewController 大小 Inferred ,在 Attribute Inspector 中将其更改为 iPhone 4 inch (Simulated Metrics -> Size 并根据该大小设置按钮框架。

希望对您有所帮助:)

当然不会显示控件。看,你在这些地方使用了两个不同的视图控制器。在 xib 中,您实际上已经添加了按钮,因此当从 xib 创建 testViewController 的实例时,它具有按钮及其关联的操作。但是,如果您在情节提要中添加 viewController 并将其 class 设置为 TestViewController 的类型,您所做的只是设置 class 类型新 view controllerTestViewController。但是您没有提供任何信息,故事板可以通过这些信息知道它必须从保存在其 XIB 中的图像创建 testViewController 的新实例。所以它只是创建了一个 TestViewController 类型的新视图控制器,使用故事板内部的图像(其中没有按钮)。

因此,要从 xib 获取视图控制器,您必须在 TestViewController 实现中覆盖 initWithCoder: 方法,并 return 来自 viewController 的实例XIB。类似于:

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
  return [self initWithNibName:nil bundle:nil];
}