2014-02-25 96 views
1

我正在試圖做一個UIView類別繪製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:」永遠不會被調用。 有什麼想法?

謝謝!

+0

一個問題:爲什麼不能繼承子類? – zaph

+0

這是一個實驗,但是子類需要「addSubview:」,並且不能用於Interface Builder。我需要最大的自由度 – mhergon

+0

瀏覽http://stackoverflow.com/questions/5272451/overriding-methods-using-categories-in-objective-c開始(TLDR你只是會導致你自己的問題) – Wain

回答