Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image not resizing in SwiftUI TabView

Tags:

ios

swiftui

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?

like image 509
codewithfeeling Avatar asked Oct 18 '19 11:10

codewithfeeling


2 Answers

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")
    }
}
like image 81
Kevin R Avatar answered Oct 11 '22 10:10

Kevin R


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

like image 5
Casper Zandbergen Avatar answered Oct 11 '22 09:10

Casper Zandbergen