【问题标题】:Getting the filename of an SKSpriteNode in Swift 3在 Swift 3 中获取 SKSpriteNode 的文件名
【发布时间】:2016-12-21 21:42:29
【问题描述】:

如何从SKSpriteNode 访问图像文件名?我一直在尝试谷歌这个,但似乎没有答案。这是我的代码中无能为力的部分:

current_ingredient?.name = String(describing: current_ingredient?.texture)

print("Filename: \(current_ingredient?.name)")

打印命令返回:

Filename: Optional("Optional(<SKTexture> \'ingredient14\' (110 x 148))")

那么,问题是,我怎样才能只得到“ingredient14”?

【问题讨论】:

    标签: swift sprite-kit swift3 skspritenode


    【解决方案1】:

    保存在 userData 中

    您可以将用于创建精灵的图像名称存储在 userData 属性中。

    let imageName = "Mario Bros"
    let texture = SKTexture(imageNamed: imageName)
    let sprite = SKSpriteNode(texture: texture)
    sprite.userData = ["imageName" : imageName]
    

    现在给定一个精灵,您可以检索您最初使用的图像的名称

    if let imageName = sprite.userData?["imageName"] as? String {
        print(imageName) // "Mario Bros"
    }
    

    【讨论】:

    • 这似乎是最安全的方式,因为如果 Apple 决定更改 description 属性的实现,则具有扩展的其他解决方案将中断并需要重写(更新)。我真的很想知道为什么从一开始就没有将纹理名称作为属性。会很有用的。
    • 我同意这是最好的,得到我的支持。唯一的缺点是 userData 是可变的,因此可能会意外覆盖它。也许静态查找表会更好。
    • @Knight0fDragon:我刚刚添加了一个更新,其中图像名称保存在单例中。
    • hmmmm,我不认为保存 SKSpriteNode 是一个好主意,最终会保留精灵。而且我们也不能使用 SKTexture,因为苹果不再在 SKTexture 对象中拉取相同的对象
    • @Whirlwind,你们中有人知道 SKTexture 的 CGimage 是否在从图集提取的多个 SKTexture 实例之间共享吗?也许可以使用那个键。
    【解决方案2】:

    它存储在描述中,所以我做了一个很好的小扩展来把它撕掉。

    extension SKTexture
    {
        var name : String
        {
            return self.description.slice(start: "'",to: "'")!
        }
    }
    
    extension String {
        func slice(start: String, to: String) -> String? 
        {
    
            return (range(of: start)?.upperBound).flatMap 
            { 
              sInd in
                (range(of: to, range: sInd..<endIndex)?.lowerBound).map 
                {
                    eInd in
                    substring(with:sInd..<eInd)
    
                }
            }
        }
    }
    usage:
    
    print(sprite.texture!.name)
    

    【讨论】:

    • 这会起作用,但如果 Apple 更改 description 属性的实现会怎样?我的意思是今天,更新很快,但仍然......
    • @Whirlwind,据我所知,没有其他方法可以从 SKTexture 中获取纹理名称,我只能说观看 Beta 版并保持最新
    • 是的,别无他法。
    • 虽然,可能会尝试在未来对扩展进行一点验证
    • 你做 body.node.name 来获取附加到 body 的节点的名称
    【解决方案3】:

    您可以使用以下扩展名从纹理描述中提取文件名

    extension SKTexture {
        var name:String? {
            let comps = description.components(separatedBy: "'")
            return comps.count > 1 ? comps[1] : nil
        }
    }
    

    用法:

    if let name = sprite.texture?.name {
        print (name)
    }
    

    【讨论】:

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