我有一个非常简单的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
Run Code Online (Sandbox Code Playgroud)
如果我在这个类上用一些非零的rect调用initWithFrame:rect,它可以正常工作; 但是当我调用initWithFrame:CGRectZero时,即使我将视图的帧修改为非零rect,也会调用drawRect.
我当然明白为什么一个零帧的视图永远不会有它的drawRect:被调用,但为什么它甚至在帧被改变之后才被调用?
Sco*_*ice 30
快速浏览Apple文档即可
更改框架矩形会自动重新显示视图而不调用其drawRect:方法.如果您希望UIKit在框架矩形更改时调用drawRect:方法,请将contentMode属性设置为UIViewContentModeRedraw.
这是在框架属性的文档中:https:
//developer.apple.com/documentation/uikit/uiview/1622621-frame?language = objc
如果你想让视图重绘,只需在它上面调用setNeedsDisplay就可以了(或者,正如文档所说,你可以将它设置为UIViewContentModeRedraw,但这取决于你)