【问题标题】:How to change text of a SKLabelNode?如何更改 SKLabelNode 的文本?
【发布时间】:2014-02-07 07:03:06
【问题描述】:

如何更新在 initWithSize 中创建的标签文本? 这是 initWithSize 中标签的代码:

SKLabelNode *scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"TimesNewRoman"];
    scoreLabel.text = [NSString stringWithFormat:@"%i", score];
    scoreLabel.fontSize = 30;
    scoreLabel.position = CGPointMake(290, CGRectGetMidY(self.frame) - 30);
    scoreLabel.zRotation = -M_PI/2;
    [self addChild:scoreLabel];

随着游戏的运行,我更新了变量分数,我只是想知道如何让标签显示新分数。

【问题讨论】:

  • 发布代码,您实际上是如何尝试更改标签文本的,您在 cmets 中提到的错误表明问题在于正确引用标签对象

标签: ios sprite-kit sklabelnode


【解决方案1】:

你必须在头文件中声明scoreLabel,然后在任何你想要的地方声明scoreLabel.text = //Your text

编辑:

在您的 .h 文件中,声明 @property (nonatomic,strong) SKLabelNode *scoreLabel;

在您的 .m 文件中,添加 @synthesize scoreLabel;

当你初始化标签时

self.scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"TimesNewRoman"];

而不是

SKLabelNode *scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"TimesNewRoman"];

【讨论】:

  • 谢谢,但我应该在哪里添加字体大小、位置等属性?因为现在我收到一条警告说“scoreLabel 的本地声明隐藏了实例变量”
  • 每当分数更新时,只需调用一个方法说:adjustScoreLabel。在那 ` - (void)adjustScoreLabel{ scoreLabel.text = //Your Text; scoreLabel.fontSize = //你的字体大小; scoreLabel.position = // 你的位置; // 你想改变 scoreLabel 的任何属性,在这里添加它们。 }`
  • 我可以编辑 scoreLabel.text,但如果我尝试放置 scoreLabel.position 或 scoreLabel.fontsize,则会出现错误。错误是“在 UILabel 类型的对象上找不到属性 'fontsize'。”当我在头文件中声明 scoreLabel 时,我实际上并没有在屏幕上创建标签吗?
  • 不,您只是在头文件中声明它。它实际上是在您执行[self.view addSubview:self.scoreLabel]; 时添加到屏幕上的。此外,您会收到错误消息,因为在 UILabel 中没有名为 fontSize 的属性。如果您转到 SKLabelNode .h 文件,是否声明了一个名为 fontSize 的属性?如果不是,那么要更改 fontSize 只需执行 self.scoreLabel.font = [UIFont fontWithName:/*fontName*/ size:/*fontSize*/];
【解决方案2】:

为您的 SKLabelNode 设置保留/强属性。然后从您的应用程序中调用任何位置

@Property(nonatomic,retain)SKLabelNode *scoreLabel;

如果你的分数值有字符串

self.scoreLabel.Text=yourscore

如果是整数

self.scoreLabel.Text=[NSString stringWithFormat:@"%d", [yourscore intValue]]];

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多