gpt4 book ai didi

ios - 如何在 Objective C 中以编程方式设置 Root View Controller ?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:31:03 31 4
gpt4 key购买 nike

我是 iOS 开发的新手,正在尝试学习如何以编程方式创建和设置 View 。

我正在尝试在 Obj-C 中做快速声明

window?.rootViewController = UINavigationController(rootViewController : ViewController()) 

项目:单 View 应用程序。尝试链接默认创建的 ViewController.h

根据 Krunals Answer,我更新了代码,但模拟器中未显示导航 Controller

Cmd+Click Controller 不会导航到 ViewController 文件

#import "AppDelegate.h"
#import "ViewController.h"

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIScreen *screen=[[UIScreen alloc]init];
UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

self.window.makeKeyAndVisible;




ViewController *controller = [[ViewController alloc] init];



window.rootViewController = [[UINavigationController alloc] initWithRootViewController:controller] ;

最佳答案

在添加(用作导航的根 Controller )到导航 Controller 堆栈之前,初始化您的 View Controller ViewController

这里是初始化简单 View Controller 的示例代码

UIViewController *controller = [[UIViewController alloc] init];

这是使用 Storyboard初始化的示例代码

ViewController *controller = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"<ViewController - string identifier of your view controller>"];

这是使用 NIB/Bundle 初始化的示例代码

ViewController *controller = [[ViewController alloc] initWithNibName:@"<ViewController - string NIB name>>" bundle:nil];

根据您的代码和以下评论,仅尝试此代码(从您的应用程序委托(delegate)启动中删除其他代码):

// make sure your NIB name is 'ViewController' 

ViewController *controller = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
if (controller != nil) {
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController: controller];
self.window.makeKeyAndVisible;
} else {
//print - your view controller is nil
}

关于ios - 如何在 Objective C 中以编程方式设置 Root View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45924367/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com