drawRect:在UIView类别中

时间:2014-02-25 23:30:24

标签: ios uiview draw categories drawrect

我正在尝试在没有子类化的情况下绘制drawRect:方法内部的UIView类别。为此,我创建了一个块来简化此任务。

以下是代码:

的UIView + DrawRectBlock.h

#import <UIKit/UIKit.h>

// DrawRect block
typedef void(^DrawRectBlock)(UIView *drawRectView, CGRect rect);

@interface UIView (DrawRectBlock)

- (void)drawInside:(DrawRectBlock)block;

@end

的UIView + DrawRectBlock.m

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

@interface UIView ()

#pragma mark - Private properties
@property DrawRectBlock drawBlock;

@end

@implementation UIView (DrawRectBlock)

- (void)drawInside:(DrawRectBlock)block {
    if ((self.drawBlock = [block copy])) {
        [self setNeedsDisplay];
    }
}

- (void)drawRect:(CGRect)rect {
    if (self.drawBlock) {
        self.drawBlock(self, rect);
    }
}

- (void)dealloc {
    self.drawBlock = nil;
}

#pragma mark - Others
- (void)setDrawBlock:(DrawRectBlock)drawBlock {
    objc_setAssociatedObject(self, @"block", drawBlock, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (DrawRectBlock)drawBlock {
    return objc_getAssociatedObject(self, @"block");
}

@end

最后,我按如下方式调用块:

[_testView drawInside:^(UIView *drawRectView, CGRect rect) {

        NSLog(@"DrawReeeeeeect!!!!");

        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
        CGContextSetLineWidth(context, 5.0);
        CGContextBeginPath(context);
        CGContextMoveToPoint(context, 0.0, 0.0); //start at this point
        CGContextAddLineToPoint(context, 100.0, 100.0); //draw to this point
        CGContextStrokePath(context);

    }];

但是从不调用“drawRect:”。 有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

最后我混合了子类和类别,效果很好! https://github.com/mhergon/SimpleBlockDrawing