Getting the SKSpriteNode File Name in Swift 3

How to access image file name with SKSpriteNode ? I tried to do this Google, but there was no answer. Here is the powerless 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 can I get only "ingredient14"?

+5
source share
3 answers

It is stored in the description, so here is a small small extension that I made to pry 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) 
+4
source

Saving inside userData h2>

You can save the name of the image that you used to create the sprite inside the userData property.

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

Now, using the sprite, you can get the name of the image that you used originally

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

You can extract the file name from the texture description with the following extension

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

Using:

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

Source: https://habr.com/ru/post/1261671/


All Articles