Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI on macOS, how to use custom image symbol on Button?

READ THE QUESTION CAREFULLY, THIS IS A MAC APP, systemName is not available on mac os

I'm trying to build a simple application using swiftUI on macOS, however I'm having some trouble displaying some icons.

I have now read everywhere that you need to download the SF Symbols app and export the symbols yourself in order to use them, so I did that, then I added the exported symbol to the .xcassets and now I'm trying to create a button with an image, so here is the code:

import SwiftUI

struct ActionBar: View {

    var body: some View {
        HStack {
            Spacer()
            Button(action: {

            }) {
                Image("Plus")
                    .font(Font.system(size: 24, weight: .light))
                    .foregroundColor(Color.red)
                Text("Test")
            }
        }
        .frame(maxWidth: .infinity)
        .padding()
        .background(Color.init(red: 0.8, green: 0.8, blue: 0.8))
    }
}

struct ActionBar_Previews: PreviewProvider {
    static var previews: some View {
        ActionBar()
    }
}

I have tried many variations, for example:

Image(nsImage: NSImage(name: "Plus"))

but all the information out there, including apples own documentation only talk about UIImage which as far as I understood is part of UIKit which is the iOS version of the UI framework, has anybody gotten this to work on macOS?

Thanks a lot!

Edit: the asset was imported as a Image Symbol Set, Xcode doesn't throw any errors as I just took the svg generated by the SF Symbols app and put it directly on the assets.

Edit 2: I just run into this post which states SVG support is wonky... I tried converting the SVG into a PNG, but xcode does not accept pngs as Symbol sets... so, I guess this feature is just plain broken? which sucks...

like image 316
Oscar Franco Avatar asked Jan 25 '23 03:01

Oscar Franco


1 Answers

In MacOS, there are no systemImages available. But NSImage.Name prov ides the alternative option. This link show most of the MacOS system default icons.

This is an example of NSImage.Name :

Icon(NSImage.refreshTemplateName)

Following is the Icon view definition :

struct Icon: View {
    var image: NSImage.Name
    var body: some View {
        Image(nsImage: NSImage(named: image)!)
            .renderingMode(.original)
            .resizable()
            .scaledToFit()
    }
    init(_ image: NSImage.Name){
        self.image = image
    }
}

P.S. Image view does not have a modifier called .font(). Please check its documentation for proper syntax.

Edit: You can skip the extra view by following format.

Image(nsImage: NSImage(name: NSImage.addTemplateName))

The list of NSImage.Names are here

like image 53
NikzJon Avatar answered Feb 08 '23 17:02

NikzJon