EN VI

How can I write a view that pulls an image from my local resources and if it is not there pull the image from SF Symbols?

2024-03-17 06:00:10
How can I write a view that pulls an image from my local resources and if it is not there pull the image from SF Symbols

I have written this to either pull my icons from my own resources in my project or pull them from SF Symbols in SwiftUI. Unfortunately, I get No such module 'UIKit'. I've also tried to import UIKit.UIImage. Has this functionality been deprecated or has it picked up and moved elsewhere? Or am I just doing this wrong?

import SwiftUI
import UIKit

struct GetImage: View {
    let name: String
    
    init(_ name: String) {
        self.name = name
    }
    
    var body: some View {
        if let image = UIImage(named: name) {
            return Image( uiImage: image )
        } else {
            return Image( systemName: name )
        }
    }
}

Edit-2 - works but doesn't allow modifiers

import SwiftUI

struct MyImage: View {
     let image: String
     
     init(_ image: String) {
          self.image = image
     }
     
     var body: some View {
         if ( NSImage(named: image) != nil ) {
            print( " ---> a" )
            return Image( image )
        } else {
            print( " ---> b" )
            return Image( systemName: image )
        }
     }
}

Solution:

The following is another approach and the code works on both macOS as well as iOS. The compiler directive addresses the NSImage/UIImage difference. The code works with images placed in the assets catalog. The code is expanded to give you more context:

import SwiftUI

#if os(iOS)
public typealias CPImage = UIImage
#elseif os(OSX)
public typealias CPImage = NSImage
#endif

struct ContentView: View {
    
    @State var name = "star"
    
    var body: some View {
        GetImage(name: $name)
            .frame(width: 100, height: 100)
    }
}

struct GetImage: View {
    @Binding var name: String
    
    var body: some View {
        
        if CPImage(named: name) != nil {
            return Image(name).resizable()
        }
        
        return Image(systemName: name).resizable()
    }
}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login