Xcode错误一直说大小未声明如何解决这个问题?

时间:2011-08-23 17:09:59

标签: xcode function

我正在将下面的代码编写成xcode并且它的大小一直未出现:首先在这个函数中使用我如何解决这个问题,以便我可以运行代码?

// on "init" you need to initialize your instance
-(id) init
{ CCSprite *spaceCargoShip = [CCSprite
                             spriteWithFile:@"spaceCargoShip.png"];
[spaceCargoShip     setPosition:ccp(size.width/2, size.height/2)];
[self addChild:spaceCargoShip];

3 个答案:

答案 0 :(得分:2)

在该函数中未声明size变量。你必须从其他地方获得它 - 也许是self.size,但是没有看到其余的代码,我不知道应该从哪里来。

答案 1 :(得分:0)

我猜你想把你的货船放在屏幕的左下角。为此,您希望使用您创建的精灵的大小,即spaceCargoShip.contentSize。

而不是

[spaceCargoShip setPosition:ccp(size.width/2, size.height/2)];

使用

[spaceCargoShip setPosition:ccp(spaceCargoShip.contentSize.width/2,
                                spaceCargoShip.contentSize.height/2)];

玩得开心!

答案 2 :(得分:0)

我遇到了同样的问题。

代码必须放在init函数和if语句中。

- (id)init {
   if (self = [super init]) {
    //Code for the spaceCargoShip
     ...
    // ask director the the window size
    CGSize size = [[CCDirector sharedDirector] winSize]; //<-- This is the "size" variable that the code is looking for.
     ...
    //Enter the code for the spaceCargoShip in here.
    CCSprite *spaceCargoShip = [CCSprite spriteWithFile:@"SpaceCargoShip.png"];
    [spaceCargoShip setPosition:ccp(size.width/2, size.height/2)];
    [self addChild:spaceCargoShip];

   }
   return self;
}

它不起作用的原因是如果你没有将变量放在if statement中,变量就会超出范围。