Как получить доступ к свойству CGColor UIColor в CGContextSetFillColorWithColor?
CGContextSetFillColorWithColor(g, [UIColor greyColor].CGColor);
Я пытаюсь следовать книге O'Reilly, разработке игр для iPhone, но на странице 73 Глава 3 Я получаю эту ошибку:
error: request for member 'CGColor' in something not a structure or union
Согласно книге странице ошибок, это неподтвержденная ошибка в книге. Какой функциональный код может заменить эту строку?
Дополнительные сведения
Пример проекта можно загрузить здесь.
Я столкнулся с ошибкой в функции рендеринга, следуя инструкциям книги со стр. 72 на стр. 73, чтобы построить класс gsMain (отличный от примерного проекта pg77) в функции рендеринга gsMain.m
Фрагмент кода, который книга поручает построить класс gsMain, следующая:
//gsMain.h
@interface gsTest : GameState { }
@end
//gsMain.m
@implementation gsMain
-(gsMain*) initWithFrame:(CGRect)frame andManager:(GameStateManager*)pManager
{
if (self = [super initWithFrame:frame andManager:pManager]) {
NSLog(@"gsTest init");
}
return self;
}
-(void) Render
{
CGContextRef g = UIGraphicsGetCurrentContext();
//fill background with gray
CGContextSetFillColorWithColor(g, [UIColor greyColor].CGColor); //Error Occurs here
CGContextFillRect(g, CGRectMake(0, 0, self.frame.size.width,
self.frame.size.height));
//draw text in black
CGContextSetFillColorWithColor(g, [UIColor blackColor].CGColor);
[@"O'Reilly Rules!" drawAtPoint:CGPointMake(10.0,20.0)
withFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];
}
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch* touch = [touches anyObject];
NSUInteger numTaps = [touch tapCount];
//todo: implement touch event code here
}
@end
Предполагается, что Chapter3_Example_p77 отображает результат упражнений со стр. 71 до 77, но он сильно отличается от заданных инструкций, приведенных в пунктах 71-77. Следующий код - это готовый, компилируемый класс, загруженный из приведенной выше ссылки.
//gsMain.h
#import <Foundation/Foundation.h>
#import "GameState.h"
@interface gsMain : GameState {
}
@end
// gsMain.m
// Example
// Created by Joe Hogue and Paul Zirkle
#import "gsMain.h"
#import "gsTest.h"
#import "Test_FrameworkAppDelegate.h"
@implementation gsMain
-(gsMain*) initWithFrame:(CGRect)frame andManager:(GameStateManager*)pManager {
if (self = [super initWithFrame:frame andManager:pManager]) {
//do initializations here.
}
return self;
}
- (void) Render {
[self setNeedsDisplay]; //this sets up a deferred call to drawRect.
}
- (void)drawRect:(CGRect)rect {
CGContextRef g = UIGraphicsGetCurrentContext();
//fill background with gray
CGContextSetFillColorWithColor(g, [UIColor grayColor].CGColor);
CGContextFillRect(g, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height));
//draw text in black.
CGContextSetFillColorWithColor(g, [UIColor blackColor].CGColor);
[@"O'Reilly Rules!" drawAtPoint:CGPointMake(10.0, 20.0) withFont:
[UIFont systemFontOfSize: [UIFont systemFontSize]]];
//fps display from page 76 of iPhone Game Development
int FPS = [((Test_FrameworkAppDelegate*)m_pManager) getFramesPerSecond];
NSString* strFPS = [NSString stringWithFormat:@"%d", FPS];
[strFPS drawAtPoint:CGPointMake(10.0, 60.0) withFont:[UIFont systemFontOfSize:
[UIFont systemFontSize]]];
}
//this is missing from the code listing on page 77.
-(void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch* touch = [touches anyObject];
NSUInteger numTaps = [touch tapCount];
if( numTaps > 1 ) {
[m_pManager doStateChange:[gsTest class]];
}
}
@end
Ответы
Ответ 1
Как насчет [ [ UIColor grayColor ] CGColor ]
?
Используете ли вы последний SDK? Я полагаю, что ваш заголовок UIColor.h
имеет свойство для CGColor
? (Я бы проверял ваши настройки SDK - когда я открыл образец проекта, он был настроен на iOS 3.x)
В Swift 3.x: UIColor.gray.cgColor
Ответ 2
Я скомпилировал пример p77
для Simulator 3.1.3 и не попал в какие-либо предупреждения или ошибки компилятора.
Код:
- (void)drawRect:(CGRect)rect {
CGContextRef g = UIGraphicsGetCurrentContext();
//fill background with gray
CGContextSetFillColorWithColor(g, [UIColor grayColor].CGColor);
CGContextFillRect(g, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height));
//draw text in black.
CGContextSetFillColorWithColor(g, [UIColor blackColor].CGColor);
[@"O'Reilly Rules!" drawAtPoint:CGPointMake(10.0, 20.0) withFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];
//...
}
похоже, скомпилировано. Возможно, вы можете указать, какой из трех примеров вы компилируете и для какой целевой версии ОС?
Ответ 3
Убедитесь, что вы #include <UIKit/UIKit.h>
.
И это -grayColor
, а не -greyColor
.