如何在通用应用程序中创建新的UIViewController

时间:2012-06-20 10:03:37

标签: iphone

我正在开发一个应用程序。我正在使用基于单一视图的应用程序模型创建通用应用程序。所以,我需要创建一个新类。但是,它只提供一个xib。 iPhone和iPad需要两个xib。请告诉我如何为单个类创建两个xib。

2 个答案:

答案 0 :(得分:3)

创建一个具有相同名称的新视图..假设您的视图控制器名称为“NewViewController”..您的xib将为NewViewController~ipad用于iPad,NewViewController~iPhone用于iphone ..所以当你实现initWithNibName只需为你的xib编写基本名称NewViewController,iOS将根据当前使用的平台调用匹配xib ..并且不要忘记为自己分配自定义类新xib中的文件所有者将成为您的新类,如下图所示。

enter image description here

对于创建新xib,请检查以下图片:

enter image description here

enter image description here

答案 1 :(得分:0)

Malek_Jundi有关于如何为iphone和ipad创建和加载.nib文件的明确指南。

如果你想为每个案例(iphone或ipad)创建不同的类,你可以使用这样的IF语句:

UIViewController *target;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
    target = [[NewViewController alloc] initWithNibName:@"NewViewController" bundle:[NSBundle mainBundle]];
} else {
    target = [[NewViewController_ipad alloc] initWithNibName:@"NewViewController" bundle:[NSBundle mainBundle]];
}

但我懒得在我的代码中反复输入“IF”语句来为iphone / ipad创建特定的类。我有另一种方式:

- (Class)idiomClassWithName:(NSString*)className
{
    Class ret;
    NSString *specificName = nil;
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        specificName = [[NSString alloc] initWithFormat:@"%@_ipad", className];
    } else {
        specificName = [[NSString alloc] initWithFormat:@"%@_iphone", className];
    }
    ret = NSClassFromString(specificName);
    if (!ret) {
        ret = NSClassFromString(className);
    }
    return ret;
}

- (void)createSpecificNewController
{
    Class class = [self idiomClassWithName:@"NewViewController"];
    UIViewController *target = [[class alloc] initWithNibName:@"NewViewController" bundle:[NSBundle mainBundle]];
    //...
}