加载特定于设备的类别

时间:2011-10-01 16:57:07

标签: iphone ipad categories universal

我有一个我想要通用的iPhone应用程序,大多数视图可以保持相同,但是需要对iPad进行一些小的修改。

是否可以根据用户使用的设备加载类别?

或者有更好的方法吗?一种通用的方式(而不是每次我创建一个类的新实例,并在2个类之间进行选择时专门检查)

2 个答案:

答案 0 :(得分:2)

你可以在运行时使用某种方法进行调整。举个简单的例子,如果你想在drawRect:子类中使用依赖于设备的UIView方法,你可以编写两个方法并决定在初始化类时使用哪个方法:

#import <objc/runtime.h>

+ (void)initialize
{
    Class c = self;
    SEL originalSelector = @selector(drawRect:);
    SEL newSelector = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
                      ? @selector(drawRect_iPad:) 
                      : @selector(drawRect_iPhone:);
    Method origMethod = class_getInstanceMethod(c, originalSelector);
    Method newMethod = class_getInstanceMethod(c, newSelector);
    if (class_addMethod(c, originalSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
        class_replaceMethod(c, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    } else {
        method_exchangeImplementations(origMethod, newMethod);
    }
}

- (void)drawRect_iPhone:(CGRect)rect
{
    [[UIColor greenColor] set];
    UIRectFill(self.bounds);
}

- (void)drawRect_iPad:(CGRect)rect
{
    [[UIColor redColor] set];
    UIRectFill(self.bounds);
}

- (void)drawRect:(CGRect)rect
{
    //won't be used
}

这会导致iPad上的红色视图和iPhone上的绿色视图。

答案 1 :(得分:0)

查看UI_USER_INTERFACE_IDIOM()宏,这将允许您根据设备类型分支代码。

如果您只想保留每个文件iPhone或iPad,则可能必须创建一个辅助类或抽象超类,它返回相应的实例。