IPhone : drawRect method get called but the UIView cannot display

on Saturday, April 18, 2015

ModeButtonView is a subclass of UIView, and is already added as a subview of viewController.view:


@interface ModeButtonView ()


@property(nonatomic, strong) MonthModeButtonView *monthModeButton;


@end


-(instancetype)initWithFrame:(CGRect)frame{



self = [super initWithFrame:frame];
if (!self) {
return nil;
}

self.backgroundColor = [UIColor colorWithRed:0.192 green:0.663 blue:0.647 alpha:1];

self.monthModeButton = [[MonthModeButtonView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.5 * self.bounds.size.width, 0.5 * self.bounds.size.height)];

self.monthModeButton.center = self.center;
[self addSubview:self.monthModeButton];

return self;


}


The MonthModeButtonView is also a subclass of UIView, and it is added as a subview of ModeButtonView. Its drawRect method is as follows:




  • (void)drawRect:(CGRect)rect {


    NSLog(@"drawRect get called");


    CGMutablePathRef path = CGPathCreateMutable();


    CGPathMoveToPoint(path, NULL, rect.origin.x, rect.origin.y);


    CGPathAddLineToPoint(path, NULL, rect.size.width, rect.size.height);


    CGPathMoveToPoint(path, NULL, rect.size.width, rect.origin.y);


    CGPathAddLineToPoint(path, NULL, rect.origin.x, rect.size.height);


    CGContextRef currentContext = UIGraphicsGetCurrentContext();


    CGContextAddPath(currentContext, path);


    [[UIColor redColor] setStroke];


    CGContextDrawPath(currentContext, kCGPathStroke);


    CGPathRelease(path);




}


I run the program, the ModeButtonView is displayed well on the screen, and the drawRect method of MonthModeButtonView also get called, however, it cannot be displayed on the screen, while I have added it as a subview of ModeButtonView.


However, if I put the code of MonthModeButtonView's drawRect method into ModeButtonView's drawRect method directly, it get displayed. It seems the problem happens because MonthModeButtonView is a subview of MoodeButtonView, but why? Any idea about that? Thanks.


0 comments:

Post a Comment