通用的iPhone/iPad应用委托

9
我想知道,如果从零开始创建一个应用程序,如何组织一个通用的(iPhone/iPad)iOS应用程序。我注意到在使用Xcode Beta的默认模板时,它会为您提供共享的AppDelegate和针对iPhone和iPad的子类appdelegates。
现在,如何放置逻辑来确定使用哪个app delegate?它如何知道要实例化和使用哪一个作为默认模板没有说明。如果我要编写iPhone的appDelegate,我怎么知道这只会在iPhone iOS上运行?

1
如果你在讨论XCode Beta,我相信那是受保密协议约束的。但这个问题或许可以帮到你:https://dev59.com/_k3Sa4cB1Zd3GeqPy-BA - Aaron Saunders
这不是一个特定于xCode Beta的问题,所以请忽略我提到的那一点。 - Doz
5个回答

13

应用程序的 Info.plist ("主 NIB 文件基本名称") 指定要加载的主窗口 .xib 文件,并且该 .xib 文件指定了应用程序的委托和根窗口控制器。

iPad 的 Info.plist("NSMainNibFile~ipad") 还额外指定了 iPad 的主窗口 .xib 文件,该文件可以包含不同的应用程序委托和不同的根窗口控制器。或者它们可以使用运行时的 UIUserInterfaceIdiomPad 检查来使用相同的委托和控制器。

运行时(知道自己在哪个设备上运行),从 info.plist 中选择正确的初始 .xib 文件进行加载,然后配置并运行正确的应用程序委托和根窗口控制器。


9
使用以下代码:
id<UIApplicationDelegate> delegate = [[UIApplication sharedApplication] delegate]; 
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    AppDelegate_iPad *appDelegate = (AppDelegate_iPad *) delegate;
else
    AppDelegate_iPhone *appDelegate = (AppDelegate_iPhone *) delegate;

无论何时需要访问委托。

我在Xcode的第三和第五行遇到了错误,指出appDelegate未声明,并且出现“意外的界面名称AppDelegate_iPhone(/iPad):预期表达式”的提示。 - Ryan Waggoner

2

Variations on a theme

Create a Common.h file

// Global Helpers
#define APP_DELEGATE()  (AppDelegate *)[[UIApplication sharedApplication] delegate]
#define APP_DELEGATE_IPAD()  (AppDelegate_iPad*) [[UIApplication sharedApplication] delegate]; 
#define APP_DELEGATE_IPHONE()  (AppDelegate_iPhone*) [[UIApplication sharedApplication] delegate]; 
#define IS_IPAD ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] && [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)

在您的预编译头文件.pch中导入Common.h / AppDelegate_iPhone.h / AppDelegate_iPad.h / AppDelegate.h 。然后在您的类中,您可以简单地调用。
if (IS_IPAD) {
      AppDelegate_iPad *appDelegate = APP_DELEGATE_IPAD();
}else{
    AppDelegate_iPhone *appDelegate = APP_DELEGATE_IPHONE();
}

1

继续Sagar的回答,这里是可以修复Ryan Waggoner评论的代码。

id<UIApplicationDelegate> delegate = [[UIApplication sharedApplication] delegate]; 
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    delegate = (AppDelegate_iPad *) delegate;
else
    delegate = (AppDelegate_iPhone *) delegate;

前面答案的问题在于它实际上没有提供在 IF 语句外部访问变量 delegate 的方法。这段代码只是将原始变量强制转换为正确的类型。

这并不实用。如果委托已经被设置,为什么还需要转换?如果不同的类中没有声明它作为一个实例,那就更不需要了。 - user529758

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接