是 - [UIView(MyOwnCategory)drawRect:]从未在3.1.3上调用过?

时间:2012-01-11 22:30:58

标签: iphone objective-c ios swizzling

我定义了自己的drawRect方法,并且在4.2.1(iOS)5.0(iOS)和4.3.2(模拟器)上进行了调用。但它从未调用过3.1.3(iPhone 2g)。

这可能是什么原因?

P.S。自从我开始写这个问题后,我认为我的3.1.3设备已经越狱了。也许这是这种奇怪行为的根本原因。

更新:为了重现问题,我使用下一个代码:

@implementation UIView (MyOwnCategory)
- (void)drawRect:(CGRect)rect
{
    const char * function = __FUNCTION__;
    [NSException raise: @"hi!" format: @"%s", function];
}
@end
即使我明确地呼叫[super drawRect: rect]

,<3.1>异常也从未发生在3.1.3上

1 个答案:

答案 0 :(得分:3)

我想写几个星期的方法杂乱,@Kevin Ballard的评论最终让我这样做(感谢你的灵感,凯文)。

所以这里是使用method swizzling解决问题的解决方案,它也适用于iOS 3.x:

<强>的UIView + Border.h:

#import <Foundation/Foundation.h>
@interface UIView(Border)
@end

<强>的UIView + Border.m:

#import "UIView+Border.h"
#import <QuartzCore/QuartzCore.h>
#import <objc/runtime.h>

@implementation UIView(Border)

- (id)swizzled_initWithFrame:(CGRect)frame
{
    // This is the confusing part (article explains this line).
    id result = [self swizzled_initWithFrame:frame];

    // Safe guard: do we have an UIView (or something that has a layer)?
    if ([result respondsToSelector:@selector(layer)]) {
        // Get layer for this view.
        CALayer *layer = [result layer];
        // Set border on layer.
        layer.borderWidth = 2;
        layer.borderColor = [[UIColor redColor] CGColor];
    }

    // Return the modified view.
    return result;
}

- (id)swizzled_initWithCoder:(NSCoder *)aDecoder
{
    // This is the confusing part (article explains this line).
    id result = [self swizzled_initWithCoder:aDecoder];

    // Safe guard: do we have an UIView (or something that has a layer)?
    if ([result respondsToSelector:@selector(layer)]) {
        // Get layer for this view.
        CALayer *layer = [result layer];
        // Set border on layer.
        layer.borderWidth = 2;
        layer.borderColor = [[UIColor blueColor] CGColor];
    }

    // Return the modified view.
    return result;
}

+ (void)load
{
    // The "+ load" method is called once, very early in the application life-cycle.
    // It's called even before the "main" function is called. Beware: there's no
    // autorelease pool at this point, so avoid Objective-C calls.
    Method original, swizzle;

    // Get the "- (id)initWithFrame:" method.
    original = class_getInstanceMethod(self, @selector(initWithFrame:));
    // Get the "- (id)swizzled_initWithFrame:" method.
    swizzle = class_getInstanceMethod(self, @selector(swizzled_initWithFrame:));
    // Swap their implementations.
    method_exchangeImplementations(original, swizzle);

    // Get the "- (id)initWithCoder:" method.
    original = class_getInstanceMethod(self, @selector(initWithCoder:));
    // Get the "- (id)swizzled_initWithCoder:" method.
    swizzle = class_getInstanceMethod(self, @selector(swizzled_initWithCoder:));
    // Swap their implementations.
    method_exchangeImplementations(original, swizzle);
}

@end