Is there a way to check if proposed systemName
has a corresponding image which is going to be rendered properly? This is necessary to display a placeholder image in case when the system doesn't contain the image in question.
Asked
Active
Viewed 48 times
0
-
1Testing, either the hardcoded string will match an image or it won't. This will never change during runtime so once it works it will work. If you need to support older versions where the image (or functionality like multi colouring) doesn't exist then you need to manually import them to your assets folder. See for instance [this answer](https://stackoverflow.com/a/62731361/9223839) – Joakim Danielson Aug 07 '23 at 14:34
-
Yes, that's how it usually goes. Although I can imagine situations when `systemName` or `name` parameters can go out of sync with assets on device. This is the reason why UI/NSImage initialisers are [failable](https://developer.apple.com/swift/blog/?id=17). Looks like is not possible to have failable inits for view structs inside @viewbuilder, but maybe there is an option to test against receiving an `EmptyView` (just an idea). – Paul B Aug 07 '23 at 16:11
-
1Again, if the asset folder content goes out of sync with the string names used this should be discovered during testing since it’s very very unlikely it happens when the app has been released. – Joakim Danielson Aug 07 '23 at 16:44
-
Totally agree, @Joakim. But right now I find it convenient (just for the particular rapid development case) to fall-through from systemName to asset name and to the placeholder systemName in the end. – Paul B Aug 07 '23 at 17:34
1 Answers
0
As quick way get a "placeholdered" Image
I made up a small extension:
extension Image {
#if os(iOS)
typealias PlatformImage = UIImage
#elseif os(macOS)
typealias PlatformImage = NSImage
#endif
init(for name: String, placeholder: String = "placeholdertext.fill") {
if let uiImage = PlatformImage(systemName: name) {
self = Image(uiImage: uiImage)
} else if let uiImage = PlatformImage(named: name){
self = Image(uiImage: uiImage)
} else {
self = Image(systemName: placeholder)
}
}
}
This way looks a bit overengineered. I would prefer to test for an EmptyView
or something like that. But it does it's job.

Paul B
- 3,989
- 33
- 46