I am using an UIImage, in which I have an Image, and I want to know the name of image.
Asked
Active
Viewed 3.5k times
18
-
4i dont think it is possible to get the name of image – The iOSDev Apr 23 '12 at 11:07
-
Answer: UIImageView - How to get the file name of the image assigned? http://stackoverflow.com/a/16885708/2316831?stw=2 – Hasan Sawaed Jun 02 '13 at 18:11
5 Answers
9
That functionality is not built-in to UIImage because images are not always loaded from files. However, you could create a custom UIImageView subclass to fit your needs.
Evan Mulawski
- 53,455
- 14
- 114
- 144
5
It is not possible. UIImage instance contains the actual image data without any reference to the filename.
Krishnabhadra
- 33,955
- 30
- 116
- 165
1
Images do not necessarily come from files or other named sources, so not all images even have a name. When you create an image from a file, you could store the name in a separate NSString*, and then refer to that stored name when necessary.
Sergey Kalinichenko
- 697,062
- 78
- 1,055
- 1,465
1
this code will help you out
NSString *imgName = [self.imgView1st image].accessibilityIdentifier;
NSLog(@"%@",imgName);
[self.imgView2nd setImage:[UIImage imageNamed:imgName]];
junaidsidhu
- 3,489
- 1
- 26
- 48
-
1this doesn't work because you have to set the accesibiliyIdentifier when assining image – Silviu St Jun 10 '14 at 14:23
-
This is definitely the right answer! People should upvote it. When loading images via local bundle, using XCAssets, the runtime itself will automatically assign the `accessibilityIdentifier` to be the same as the asset name. When loading images dynamically or creating it dynamically, of course there is no built-in solution – user464230 Apr 05 '22 at 16:15
0
On later iOS versions it's possible to extract image name from the description. Aware, for the debug use only!
extension UIImage {
/// Extracts image name from a description.
/// * Example description: `<UIImage:0x60000278ce10 named(main: ic_timeline_milestone_bluedot) {16, 16}>`
/// * Example name: `ic_timeline_milestone_bluedot`
/// - warning: For the debug use only.
var name: String? {
let description = self.description
guard let regexp = try? NSRegularExpression(pattern: "\\(main: (.*)\\)", options: []) else { return nil }
guard let match = regexp.matches(in: description, options: [], range: description.fullRange).first else { return nil }
guard match.numberOfRanges > 0 else { return nil }
let idx1 = description.index(description.startIndex, offsetBy: range.lowerBound)
let idx2 = description.index(description.startIndex, offsetBy: range.upperBound)
return String(description[idx1..<idx2])
}
}
Anton Plebanovich
- 1,122
- 15
- 15