简体   繁体   中英

Image not resizing in SwiftUI TabView

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.

显示大主页图标的屏幕截图

It works fine when the Image is an SF Symbol.

Any ideas, SwiftUI ninjas?

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.

从 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.

用自定义符号替换符号

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

清理 SVG 并导出

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")
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM