【问题标题】:Creating a new ViewController and xib for programmatic display (with addSubview)为编程显示创建新的 ViewController 和 xib(使用 addSubview)
【发布时间】:2010-08-21 05:20:30
【问题描述】:

我正在编写一个供 iPhone 开发人员使用的库(类似于实现 OpenFeint 的方式),并且我正在尝试创建一个带有关联 XIB 的 ViewController,以便我可以在我的代码中实例化它

SplashScreenViewController *splashScreenViewController = [[SplashScreenViewController alloc] init];
UIWindow *topApplicationWindow = [self getTopWindow];
[topApplicationWindow addSubview:splashScreenViewController.view];

然而,虽然这适用于简单的控件(UIButtons 等),但我的 SplashScreenViewController 没有显示任何内容。 SplashScreenViewController 很简单:

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>


@interface SplashScreenView : UIViewController {
}

@end

并且实现是空的。在我的 View XIB (SplashScreenView.xib) 中,我尝试将 File's Owner 的类设置为 SplashScreenViewController 这不起作用,然后我尝试了我在 OpenFeint 中看到的方法,即在 IB 中添加一个 View Controller 和将主 UIView 设为其子级,并将其设为 SplashScreenViewController 类。这也不起作用(不显示)。

我想知道是否有人对我可能遗漏的内容有一个好主意,或者是否有人可以推荐一个演练以按照我尝试的方式创建新的 ViewController。

谢谢!

【问题讨论】:

    标签: iphone cocoa-touch uikit openfeint


    【解决方案1】:

    尝试两件事:

    1. 调用 initWithNibName 而不仅仅是 init。也许您所说的 OpenFeint 覆盖了 init 以调用 initWithNibName ,这就是您看不到它的原因。

    2. 将 SplashScreenViewController 设置为您的文件所有者,并将他的视图出口连接到您的 在 IB 中查看。

    希望对你有帮助。

    【讨论】:

    • init 只是做initWithNibName:nil bundle:nil。当nibName为nil时,默认loadView使用类名(大概是[[self class] description]或者[self className])。
    • 这仍然可能是问题所在。请注意,他的 xib 将其命名为“SplashScreenView.xib”,而他的控制器类是“SplashScreenViewController”。我假设他手写的 m 文件是错误的,否则我不知道为什么 SplashScreenView 会从 UIViewController 继承。
    • 我重写了代码以更适用于这个问题,而不是使用我需要在我的项目中重构的名称。所以,是的。 XIB 名称与实际库中的 ViewController 名称不同。对这种混乱感到抱歉。你的建议确实有效。 OpenFeint 似乎在不使用initWithNibName:bundle: 的情况下做到了这一点,所以我暂时将这个问题保持开放。如果有人知道如何在不使用initWithNibName:bundle: 的情况下做到这一点,我会检查它作为答案。否则,我会检查这个。
    • 我没有得到你的新问题 - 如果现在一切正常 - 你的新问题是什么?您可以绕过调用 initWithNibName,就像我在回答中所说的那样,通过覆盖它来调用 [self init] ,然后在 init 中调用您的 initWithNibName。无论哪种方式,如果您使用的是 nib 文件,则必须在某个地方调用 initWithNibName。 (或者像 tc 说的,它将通过调用 init 使用默认参数调用)
    • 好吧,我想看看它是如何在 OpenFeint 中完成的,不需要显式设置 nib 名称,而是通过将 SplashScreenViewController 指定为类型在 Interface Builder 中隐式设置。推理只是为了约定,因为我相信这通常是开发人员习惯于连接它的方式(我确定)。
    【解决方案2】:

    试试[SplashScreenViewController alloc],而不是[splashScreenViewController alloc]。我很惊讶你没有收到编译器警告。

    【讨论】:

    • 我在插入代码时使用了一些创意来提高可读性,但我打错了 alloc 语句。它实际上是我的代码中的 [SplashScreenViewController alloc]。对不起
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2015-10-05
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 2021-04-11
    • 2019-01-20
    相关资源
    最近更新 更多