我有一个非常简单的 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
如果我用一些非零矩形在此类上调用 initWithFrame:rect ,它就可以正常工作;但是当我调用 initWithFrame:CGRectZero 时,即使在我将视图的框架修改为非零矩形之后,也永远不会调用drawRect。
我当然理解为什么零帧的视图永远不会调用它的drawRect:,但是为什么即使在帧更改之后它也不会被调用?
快速浏览一下苹果文档就知道了这一点
更改框架矩形会自动重新显示视图,而无需调用其drawRect:方法。如果您希望 UIKit 在框架矩形发生变化时调用 drawRect: 方法,请将 contentMode 属性设置为 UIViewContentModeRedraw。
这是在框架属性的文档中:
https://developer.apple.com/documentation/uikit/uiview/1622621-frame?language=objc https://developer.apple.com/documentation/uikit/uiview/1622621-frame?language=objc
如果您希望视图重绘,只需调用 setNeedsDisplay 就可以了(或者,正如文档所说,您可以将其设置为 UIViewContentModeRedraw,但这取决于您)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)