我做了一個名爲MiniView的UIView子類。UIView不會出現和drawRect方法從來沒有叫
我嘗試如下其添加到我的viewController:
@interface SomeViewController()
@property (strong, nonatomic) MiniView *miniView;
@end
- (void)viewDidLoad
{
[super viewDidLoad];
self.miniView = [[MiniView alloc] initWithFrame:CGRectMake(20.f, 20.f, 200.f, 200.f)];
_miniView.backgroundColor = [UIColor blackColor];
[self.view addSubview:_miniView];
}
的MiniView中類看起來是這樣的:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
NSLog(@"DRAW RECT");
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor * redColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
CGContextSetFillColorWithColor(context, redColor.CGColor);
CGContextFillRect(context, self.bounds);
}
但drawRect中不會被調用,除非我明確地把它從內setNeedsLayout方法。它也沒有畫任何東西。我試着在drawRect方法中添加一個UIImageView,這看起來很好。但上面的代碼什麼也沒有產生。
我也得到了錯誤:如果我打印drawRect方法和輸出的「矩形」值的日誌語句
: CGContextSetFillColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.
,它在200×200是正確的,所以我不知道爲什麼上下文是0x0。
所以一個問題是,drawRect中不會被調用,而另一個問題是,如果我明確地調用它,什麼也不顯示...
啊,我才意識到我在做什麼錯了 - 我已經重新定義了setNeedsDisplay方法在我的班級MiniView中NSLog的到的東西。所以它表現不正確。我把爲[超級setNeedsDisplay]一個電話,現在,它的工作原理*拍打頭部* – Smikey