如何解决如果初始帧为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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。