How to center a SF Symbols image vertically in UITabBarItem?
Asked Answered
O

3

6

I am using SF Symbols images as tab images in my iOS app by assigning them as follows:

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?

Overwhelming answered 1/10, 2019 at 12:51 Comment(0)
C
11

Apparently SF symbols are rendered with system font size by default. 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)
Collator answered 14/1, 2020 at 10:12 Comment(2)
For some symbols the right offset must be chosen manually - but yes, that's the right solution. Thanks!Overwhelming
Finally a solution that works. Thanks a lot! Ps. min iOS 13 required.Whereabouts
X
6

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:

self.tabBarItem.image = UIImage(systemName: "ellipsis", withConfiguration: 
UIImage.SymbolConfiguration(weight: .black))!.imageWithoutBaseline()
Xanthous answered 20/2, 2021 at 23:27 Comment(1)
imageWithoutBaseline() did the trick for me. thanks.Anglicize
G
0

You have to set the image insets on the UITabBarItem to shift your icons down 6 or 7px (depending on your icon size).

In code:

I've done this by creating a subclass of UITabBarController and adding this code to the bottom of my viewDidLoad method:

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

In storyboards:

You can also do it using storyboards by selecting your TabBarItem in the storyboard and adjusting the insets in the info panel:

Adjusting image insets in Storyboard

Gopak answered 21/11, 2019 at 15:50 Comment(1)
Unfortunately, it seems that imageinset values from the storyboard are not applied to SF Symbols images.Chivaree

© 2022 - 2024 — McMap. All rights reserved.