我要做的是点击一个按钮(在代码中创建的),并让它调用一个不同的视图控制器,然后让它在新的视图控制器中运行一个函数。

我知道这在IB中相对容易完成,但这不是一个选择。

我想做的一个例子是,如果你有两个视图控制器一个带有房子的启动画面。另一个视图控制器有一个房子的遍历你可以按照设定的顺序遍历所有的房间。在启动画面中,每个房间都有按钮,玩家可以在游戏中跳跃到任意地点。


当前回答

NSObject <UIApplicationDelegate> * universalAppDelegate = 
    ( NSObject <UIApplicationDelegate> * ) [ [ UIApplication sharedApplication ] delegate ];

它避免了在任何地方都包含你的appdelegate。h。 这是一个很简单的类型转换,允许开发独立的Controller并在其他地方重用它们,而不用担心类名等等……

享受

其他回答

2020年,iOS13, xCode 11.3。在Objective-C中工作的是:

#进口“AppDelegate.h”

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

这对我很有效,我希望你也一样!: D

如果有人想知道如何在swift中做到这一点:

if let myDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
   myDelegate.someMethod()
}

遵循以下步骤

1.在你的类中导入你的app委托对象。

#import "YourAppDelegate.h"

2.在你的类中创建一个你的app委托对象的实例(它基本上是一个单例)。

YourAppDelegate *appDelegate=( YourAppDelegate* )[UIApplication sharedApplication].delegate;

3.现在使用选择器调用方法

if([appDelegate respondsToSelector:@selector(yourMethod)]){

        [appDelegate yourMethod];
    }

或直接通过

[appDelegate yourMethod];

为迅速

let appdel : AppDelegate = UIApplication.shared.delegate as! AppDelegate

我推荐第一个。跑和走。

听起来你只需要一个UINavigationController设置?

你可以在程序的任何地方通过

YourAppDelegateName* blah = (YourAppDelegateName*)[[UIApplication sharedApplication]delegate];

在你的应用委托中,你应该通过IB或代码来设置导航控制器。

在代码中,假设你已经创建了你的“House overview”视图控制器,它会像这样在你的AppDelegate didFinishLaunchingWithOptions…

self.m_window = [[[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds] autorelease];
self.m_navigationController = [[[UINavigationController alloc]initWithRootViewController:homeViewController]autorelease];
[m_window addSubview:self.m_navigationController.view];

在此之后,你只需要每个“房间”一个视图控制器,并在按钮单击事件被选中时调用以下命令…

YourAppDelegateName* blah = (YourAppDelegateName*)[[UIApplication sharedApplication]delegate];
[blah.m_navigationController pushViewController:newRoomViewController animated:YES];

我没有测试上面的代码,所以请原谅任何语法错误,但希望伪代码是有帮助的…

Swift 3.0及更高版本更新

//
// Step 1:- Create a method in AppDelegate.swift
//
func someMethodInAppDelegate() {

    print("someMethodInAppDelegate called")
}

下面从控制器调用上述方法

//
// Step 2:- Getting a reference to the AppDelegate & calling the require method...
//
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {

    appDelegate.someMethodInAppDelegate()
}

输出: