2011-10-01 79 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