嘿伙计们,我正试图让我的应用程序在调用某个方法时加载新 View 。在方法里面我有代码:
ViewController *GameOverViewController = [[ViewController alloc] init];
[self presentViewController:GameOverViewController animated:YES completion:nil];
直接取自 How to switch views programmatically in a ViewController? (XCode iPhone) .
无论如何,当我尝试从我的 切换时 View Controller 将 Game 调用到名为 的 View Controller GameOverViewController 我只是得到很多错误。主要是
"Unknown receiver 'ViewController'; did you mean 'UIViewController'
我的应用程序崩溃了。我显然做错了什么,但我不知道那到底是什么。我是否必须声明 GameOverViewController 在我的 Game.h 或我的 appDelegate 中还是什么?
编辑:两个 View Controller 都在同一个 main.Storyboard 归档,如果这很重要
最佳答案
未知的接收者消息意味着它找不到名为 ViewController
的 View Controller 类的类定义。 .这真的是您用于“游戏结束” View Controller 的类的名称吗?如果是这样,您是否完成了 #import "ViewController.h"
在这个 .m
的开头文件?
根本问题是它找不到名为 ViewController
的类。 .
除此之外,我们一般不会使用 alloc
实例化新的 View Controller 。和 init
不再,因为那个答案可能已经暗示了。这是一种用于 NIB 的技术(仅当 NIB 名称与类名称匹配时才有效)。
对于新开发人员,我可能会鼓励您从 Storyboard开始。任何现代教程都应该引导您了解如何使用 Storyboard。 (谷歌“iOS Storyboard教程”你可能会得到很多点击。)
例如,如果您的 Storyboard有一个“ Storyboard标识符”为 GameOverViewController
的场景。 ,那么您可以以编程方式对其进行实例化,并以如下方式呈现它:
UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"GameOverViewController"];
[self presentViewController:controller animated:YES completion:nil];
或者,如果您的 Storyboard 有从当前场景到下一个场景的转场,您需要确保转场有自己的 Storyboard 标识符,例如
GameOverSegue
,然后你会像这样执行它:[self performSegueWithIdentifier:@"GameOverSegue" sender:self];
但是在 Storyboard上找到一个很好的介绍/教程,因为在 Stack Overflow 中跌跌撞撞地寻找答案并不是一个很有成效的练习。
出于历史目的,值得注意的是,如果您使用的是 NIB,则可以使用您在问题中引用的构造(但您必须确保 (a) 类名是正确的;并且 (b) 您做到了
#import
那个类头)。如果目标 NIB 的名称与类不同,则必须执行以下操作:UIViewController *controller = [[NSBundle mainBundle] loadNibNamed:@"nibname" owner:self options:nil]`;
[self presentViewController:controller animated:YES completion:nil];
但这都是学术性的,除非您使用的是 NIB。如果使用 Storyboard ,如果您需要以编程方式过渡到新场景,请使用上述模式之一。
关于ios - 如何以编程方式转换到不同的 View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26621320/