I have an iPhone app that I'd like to make universal, most views can be kept the same, but there are some minor modifications that need to be made for the iPad.
Is it possible to load a category depending on what device the user is using?
Or is there a better way of doing this? A generic way (rather than specifically checking each time I create a new instance of a class, and choosing between 2 classes)
You could do this with some method swizzling at runtime. As a simple example, if you want to have a device-dependent drawRect:
method in your UIView
subclass, you could write two methods and decide which to use when the class is initialized:
#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
}
This should result in a red view on the iPad and a green view on the iPhone.