简体   繁体   English

如何在 UITabBarItem 中垂直居中 SF Symbols 图像?

[英]How to center a SF Symbols image vertically in UITabBarItem?

I am using SF Symbols images as tab images in my iOS app by assigning them as follows:我在 iOS 应用程序中使用 SF Symbols 图像作为选项卡图像,方法如下:

self.tabBarItem.image = UIImage(systemName: "ellipsis")  

This results in all images being top-aligned, but I would like to have them centered vertically.这导致所有图像都是顶部对齐的,但我想让它们垂直居中。

What do I have to do for this?我该怎么做?

Apparently SF symbols are rendered with system font size by default.显然 SF 符号默认使用系统字体大小呈现。 So if you add a baseline offset of half that size to the ellipsis symbol you could almost perfectly center it vertically that way.因此,如果您将一半大小的基线偏移量添加到省略号符号,您几乎可以完全以这种方式将其垂直居中。

It's only almost perfect because ellipsis symbol has a height of its own which is not accounted for by this solution, even if it is not much.它几乎是完美的,因为省略号符号有它自己的高度,这个解决方案没有考虑到,即使它并不多。

self.tabBarItem.image = UIImage(systemName: "ellipsis")!.withBaselineOffset(fromBottom: UIFont.systemFontSize / 2)

The best solution, which will make your button identical to "tabBarSystemItem: .more", but with the possibility of removing the title and applying Configuration is the following:最好的解决方案,这将使您的按钮与“tabBarSystemItem:.more”相同,但可以删除标题并应用配置如下:

self.tabBarItem.image = UIImage(systemName: "ellipsis", withConfiguration: 
UIImage.SymbolConfiguration(weight: .black))!.imageWithoutBaseline()

You have to set the image insets on the UITabBarItem to shift your icons down 6 or 7px (depending on your icon size).您必须在UITabBarItem上设置图像插图以将您的图标向下移动 6 或 7 像素(取决于您的图标大小)。

In code:在代码中:

I've done this by creating a subclass of UITabBarController and adding this code to the bottom of my viewDidLoad method:我通过创建UITabBarController的子类并将此代码添加到我的viewDidLoad方法的底部来完成此操作:

tabBar.items?.forEach({
  $0.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
})

(You could also do this in your ViewController classes, if that's where you configure each of their tab bar items.) (您也可以在 ViewController 类中执行此操作,如果您在其中配置每个选项卡栏项。)

In storyboards:在故事板中:

You can also do it using storyboards by selecting your TabBarItem in the storyboard and adjusting the insets in the info panel:您也可以通过在 storyboard 中选择 TabBarItem 并调整信息面板中的插图来使用情节提要:

在 Storyboard 中调整图像插入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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