【问题标题】:How do you store integer values in a SKLabelNode如何在 SKLabelNode 中存储整数值
【发布时间】:2017-08-07 08:28:12
【问题描述】:

我正在尝试将整数值存储在 SKLabelNode 中,但我不断收到一个错误,我只能存储字符串。我稍后需要它作为整数。这是我的代码:

import SpriteKit
import GameplayKit

class GameScene: SKScene {

override func didMove(to view: SKView) {

    var comScore = SKLabelNode()
    comScore.fontName = "Pong Score"
    comScore.text = 0
    comScore.fontSize = 100
    comScore.color = SKColor.white
    comScore.position = CGPoint(x: 200, y: 220)
    comScore.zPosition = 3
    addChild(comScore)

}
}

如果我是 SpriteKit 的新手,我们将不胜感激。

【问题讨论】:

    标签: ios sprite-kit sklabelnode


    【解决方案1】:

    SKLabelNodetext 属性是字符串,而不是 Int。您可以通过添加引号使其成为字符串:

    comScore.text = "0"
    

    或者您可以将 Int 变量转换为字符串:

    comScore.text = String(myIntValue)
    

    【讨论】:

      【解决方案2】:

      我通过将其存储为 String initaly 来解决此问题,然后使用以下代码来回转换它:

      var comScoreInt: Int = Int(comScore.text!)!
      comScoreInt += 1
      comScore.text = String(comScoreInt)
      

      【讨论】:

        【解决方案3】:

        除了关于 Ints 和 Strings 的其他答案之外,如果您在分数上添加属性观察器,则可以在更新分数时自动更新标签:

        var comScoreInt: Int {
           didSet{
              comScore.text = String(comScoreInt)
              }
           }
        

        编辑:

        如果根据您自己的回答,您想从分数标签中的值初始化分数,则将整数分数设为计算属性:

        var comScoreInt -> Int {
           get {
              return Int(comScore.text!)
               }
           set(newScore) {
              comScore.text = String(newScore)
              }
           }
        

        现在您可以检索 comScoreInt,它会返回分数标签中的值并设置 comScoreInt,它会更新标签。

        【讨论】:

          【解决方案4】:

          斯威夫特 3 扩展是你的朋友:

          extension String {
              func integerValue() > Int? {
                  return Int(trimmingCharacters(.whitespacesAndNewlines))
          
              }
          
              static func + (left: String, right: Int) -> String {
                  guard let value = left.integerValue() else {return left}
                  return "\(value + right)"
              }
          
              static func += (inout left: String, right: Int) {
                  left = left + right
              }
          }
          

          现在您可以通过 label.text += 1 快速添加到字符串中

          这样做你最终会失去一些保护,因为你通常会期望String + Int 给你一个错误,所以你可能想考虑这个过程的安全性,也许是String 的子类NumberString 这样只能用 Int 添加某种类型的字符串, 或在提供的扩展中添加一些错误处理。

          您甚至可以更进一步,从字符串中解析出 Int(例如“Points: 1”)并更改值。

          此答案不应被视为解决您的问题的明确答案,我基本上提供了一个您可能希望在开发中考虑的基本构建块替代方案。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-02-10
            • 2013-09-02
            • 2011-01-16
            • 2017-08-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多