雖然在了XCode 4.6.3運行的iOS版本的程序,我不斷收到錯誤一長串類似如下:無效的情況下錯誤
Jul 20 13:24:40 ps2xipas3qfe Chess[277] <Error>: CGContextSetRGBFillColor: invalid context 0x0
Jul 20 13:24:40 ps2xipas3qfe Chess[277] <Error>: CGContextFillRects: invalid context 0x0
這裏是產生錯誤的代碼:
- (void)drawRect: (CGRect)rect {
//[super drawRect:rect];
for(int i=0; i<8; i++) {
for(int j=0; j<8; j++) {
CGRect TheRect = CGRectMake(i*30+30,j*30+30,30,30);
CGContextRef context = UIGraphicsGetCurrentContext();
if(i%2 == j%2) {
CGContextSetRGBFillColor(context,1.0,0.0,0.0,0.0);
}
else {
CGContextSetRGBFillColor(context,0.0,0.0,0.0,0.0);
}
CGContextFillRect(context,TheRect);
}
}
}
當我搜索的網頁爲「無效的上下文」的錯誤,我得到的答案是,一個圖形上下文只能從「的drawRect」成員函數中進行檢索,但這是一個「的drawRect內「功能,我仍然收到錯誤。這裏的課程是從UIView
繼承的ChessBoard
。
感謝您的幫助,但我無法讓我的程序運行,我很困惑。我不再得到我曾經得到的錯誤,但我現在只能看到一個空白屏幕。我試過setNeedsDisplay
和setNeedsDisplayInRect
,但他們都沒有工作。
這是一個功能我在ChessViewController.m
:
- (void)viewDidLoad
{
[super viewDidLoad];
ChessBoard* TheBoard = [ChessBoard new];
[self.view addSubview: TheBoard];
// [TheBoard setNeedsDisplayInRect: CGRectMake(0,0,400,400)];
[TheBoard setNeedsDisplay];
}
這是一個功能我在ChessBoard.m
:
- (void)drawRect: (CGRect)rect {
[super drawRect:rect];
UILabel* HelloWorld = [UILabel new];
HelloWorld.text = @"Hello, World!";
[HelloWorld sizeToFit];
HelloWorld.frame = CGRectMake(1,1,100,20);
[self addSubview:HelloWorld];
for(int i=0; i<8; i++) {
for(int j=0; j<8; j++) {
CGRect TheRect = CGRectMake(i*30+30,j*30+30,30,30);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextFillRect(context,TheRect);
if(i%2 == j%2) {
CGContextSetRGBFillColor(context,1.0,0.0,0.0,1.0);
}
else {
CGContextSetRGBFillColor(context,0.0,0.0,0.0,1.0);
}
}
}
}
是的,我明確調用'drawRect'。我沒有意識到我不應該這樣做。 – user1672637
切勿調用'drawRect:'。它甚至在'UIView drawRect:'的文檔中告訴你這一點。如果你想強制一個視圖再次繪製自己,請在視圖上調用'setNeedsDisplay'。查看Josh引用的重複內容。 – rmaddy