24

I'm trying to use a custom icon in a SwiftUI TabView. I can't see what's wrong with this code – I've included resizable on the image, yet it does not scale down.

HomeView()
          .tag(0)
          .tabItem {
            VStack {
              Image("tab-home")
                .resizable()
                .aspectRatio(CGSize(width: 20, height: 20), contentMode: .fit)
              Text("Home")
            }

          }

When I view this, the image is full size.

Screenshot showing large home icon

It works fine when the Image is an SF Symbol.

Any ideas, SwiftUI ninjas?

2 Answers 2

9

If you can accept the system choosing the image size for you, you can actually add a custom Symbol Image Set to achieve this. You can use any vector icon as your base.

Export an existing symbol

To get a hold of the symbol template we need, you can open the SF Symbols app, select an icon and export it.

Export a symbol from SF Symbols

Edit in sketch

Open in Sketch (or another tool of your choice). Notice there's a distinct struture defined. We'll need to follow this structure. In the middle, there's a size named 'Regular-M', defining this one will suffice for our purposes. Open the 'Shape' group and place your Path elements in there.

Replace symbol with custom one

You can remove the other sizes. Then, make the whole page exportable and export as SVG.

Clean up SVG and export

Import in Xcode

In your XCAsset file, add a new Symbol Image Set and drag-and-drop the newly created SVG file into there.

Now, you can simply refer to the image using the name you defined in your XCAsset file as you would expect. The image sizes automatically and will properly use accent colors:

TabView {
    Text("Hello, world 1").tabItem {
        Image("your.image.name")
        Text("title1")
    }
}
1
  • I have been doing this but when using the custom symbol in a TabView, the image is smaller than it should, actually this is the case even if I skip the edit step (export SFSymbol SVG, then directly import it in Xcode as Symbol asset without edit). Any idea why ?
    – Kuringan
    Commented Apr 19, 2021 at 0:30
7

This was the same in UIKit and the solution is to just use the right sizes for your images;

https://stackoverflow.com/a/29874619/3393964

3
  • Thanks. I thought it had maybe been solved in SwiftUI but no. Commented Oct 18, 2019 at 12:50
  • 1
    Yes you can solve it actually just use .renderingMode(.original)
    – AYohannes
    Commented Apr 19, 2020 at 5:04
  • This does not work for me. Using .renderingMode(.original) does not make the image scale (but does apply "original" rendering mode (i.e. ignore foregroundStyle/tint)).
    – Henrik
    Commented Jul 22 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.