如果初始帧为CGRectZero,则不会调用自定义UIView的drawRect

问题描述

| 我有一个非常简单的UIView自定义子类:
#import \"BarView.h\"
#import <QuartzCore/QuartzCore.h>

@implementation BarView

@synthesize barColor;

- (void)drawRect:(CGRect)rect
{
    NSLog(@\"drawRect\");
    // Draw a rectangle.
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,self.barColor.CGColor);
    CGContextBeginPath(context);
    CGContextAddRect(context,self.bounds);
    CGContextFillPath(context);
}

- (void)dealloc
{
    self.barColor = nil;

    [super dealloc];
}

@end
如果我使用一些非零的rect对该类调用initWithFrame:rect,它将正常工作;但是当我调用initWithFrame:CGRectZero时,即使我将视图的帧修改为非零矩形,也不会调用drawRect。 我当然理解为什么零框架视图永远不会调用drawRect:但是为什么即使框架更改后也不会调用它?     

解决方法

        快速浏览一下Apple文档说   更改框架矩形会自动重新显示视图,而无需调用其drawRect:方法。如果希望UIKit在框架矩形更改时调用drawRect:方法,请将contentMode属性设置为UIViewContentModeRedraw。 这在frame属性的文档中: https://developer.apple.com/documentation/uikit/uiview/1622621-frame?language=objc 如果您想重绘视图,只需在其上调用setNeedsDisplay即可,您应该可以(或者,如文档所述,您可以将其设置为UIViewContentModeRedraw,但由您自己决定)     ,        在Swift 5中
override init(frame: CGRect) {
      super.init(frame: frame)

      contentMode = UIView.ContentMode.redraw