[英]Custom UIView's drawRect never called if initial frame is CGRectZero
我有一個非常簡單的 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
如果我用一些非零矩形在這個 class 上調用 initWithFrame:rect,它工作正常; 但是當我調用 initWithFrame:CGRectZero 時,drawRect 永遠不會被調用,即使在我將視圖的框架修改為非零矩形之后也是如此。
我當然理解為什么一個零幀的視圖永遠不會調用它的 drawRect:,但是為什么即使在幀改變之后它也不會被調用呢?
快速瀏覽一下 Apple 文檔就說明了這一點
更改框架矩形會自動重新顯示視圖,而無需調用其 drawRect: 方法。 如果希望 UIKit 在框架矩形發生變化時調用 drawRect: 方法,請將 contentMode 屬性設置為 UIViewContentModeRedraw。
這是在框架屬性的文檔中:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.