2011-10-01 83 views
1

我有一个iPhone应用程序,我想使其具有通用性,大多数视图可以保持不变,但需要对iPad进行一些小修改。特定于设备的加载类别

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

或者有没有更好的方法来做到这一点?一种通用的方法(而不是每次创建一个类的新实例并在两个类之间进行选择时专门检查)

回答

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上观看绿色视图。

+0

谢谢我刚开始意识到这一点,它的功能非常强大:) –

0

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

您可能需要创建一个帮助程序类或抽象超类,如果您只想保留每个文件iPhone或iPad,就会返回相应的实例。

+0

我意识到这一点,但这会使代码非常混乱。我宁愿有一组文件,这些文件只能为iPad用户加载并覆盖iPhone代码的某些方法。 –

+2

我不确定通用应用程序的可能性 - 显然没有什么可以在编译时检查以指示设备,所以我认为所有的代码和资产都是无处不在的。 – jrturton