问题
How can I access the image filename from an SKSpriteNode
? I have been trying to Google this, but no answer seems to be available. Here is the impotent part of my code:
current_ingredient?.name = String(describing: current_ingredient?.texture)
print("Filename: \(current_ingredient?.name)")
The print command returns this:
Filename: Optional("Optional(<SKTexture> \'ingredient14\' (110 x 148))")
So, the question is, how do I get only "ingredient14"?
回答1:
It is stored in the description, so here is a nice little extension I made to rip it out.
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)
回答2:
Saving inside userData
You can store the image name you used to create a sprite inside the userData
property.
let imageName = "Mario Bros"
let texture = SKTexture(imageNamed: imageName)
let sprite = SKSpriteNode(texture: texture)
sprite.userData = ["imageName" : imageName]
Now given a sprite you can retrive the name of the image you used originally
if let imageName = sprite.userData?["imageName"] as? String {
print(imageName) // "Mario Bros"
}
回答3:
You can extract the file name from the texture's description with the following extension
extension SKTexture {
var name:String? {
let comps = description.components(separatedBy: "'")
return comps.count > 1 ? comps[1] : nil
}
}
Usage:
if let name = sprite.texture?.name {
print (name)
}
来源:https://stackoverflow.com/questions/41272365/getting-the-filename-of-an-skspritenode-in-swift-3