【发布时间】:2011-11-29 02:47:13
【问题描述】:
我有一个想要通用的 iPhone 应用程序,大多数视图可以保持不变,但需要为 iPad 进行一些小的修改。
是否可以根据用户使用的设备加载类别?
或者有更好的方法吗?一种通用的方式(而不是每次创建一个类的新实例时都专门检查,并在 2 个类之间进行选择)
【问题讨论】:
标签: iphone ipad categories universal
我有一个想要通用的 iPhone 应用程序,大多数视图可以保持不变,但需要为 iPad 进行一些小的修改。
是否可以根据用户使用的设备加载类别?
或者有更好的方法吗?一种通用的方式(而不是每次创建一个类的新实例时都专门检查,并在 2 个类之间进行选择)
【问题讨论】:
标签: iphone ipad categories universal
查看UI_USER_INTERFACE_IDIOM() 宏,这将允许您根据设备类型对代码进行分支。
如果您只想保留 iPhone 或 iPad 上的每个文件,您可能必须创建一个帮助程序类或抽象超类来返回适当的实例。
【讨论】:
您可以通过在运行时调配一些方法来做到这一点。举个简单的例子,如果你想在你的 UIView 子类中拥有一个设备相关的 drawRect: 方法,你可以编写两个方法并决定在初始化类时使用哪个方法:
#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 上的视图为绿色。
【讨论】: