How to change the TabBarItem background color - ios

I'm trying to change the background of a TabBarItem or to make a whole Image which take all the space.
Like the example below :
Do You have an Idea how to do that in swift

Swift:
//change icon and title color
UITabBar.appearance().tintColor = UIColor.redColor()
//change background default color
UITabBar.appearance().barTintColor = UIColor.blackColor()
//change selected background image
UITabBar.appearance().selectionIndicatorImage = UIImage(named: "tabSelected")

in swift 4.2 with iOS 12.1
func setUpSelectionIndicatorImage(withColors colors: [UIColor]) {
//Make selection indicator image from color and set it to tabbar
let singleTabWidth: CGFloat = self.tabBar.frame.size.width / CGFloat(self.tabBar.items?.count ?? 1)
let height = DeviceType.IS_IPHONE_X ? 55 : self.tabBar.frame.size.height
let singleTabSize = CGSize(width:singleTabWidth , height: height)
let edgeInsets = DeviceType.IS_IPHONE_X ? UIEdgeInsets(top: 1, left: 0, bottom: 0, right: 0) : .zero
self.tabBar.selectionIndicatorImage = UIImage.gradient(size: singleTabSize, colors: colors)?.resizableImage(withCapInsets: edgeInsets)
}
override func viewDidLayoutSubviews() {
let colors = [UIColor.white, UIColor.green]
setUpSelectionIndicatorImage(withColors: colors)
}

Related

Progressview tintColorIssue

I have created a progressview according to number images as you can see in below code.
let view = UIView()
view.backgroundColor = .clear
let progressView = UIProgressView(frame: CGRect(x: 0, y: 0, width: frameOfParentView.width/3 - 8, height: 30))
progressView.progressViewStyle = .default
progressView.progress = 0.0
progressView.tintColor = .red
progressView.trackTintColor = .gray
progressView.layoutIfNeeded()
view.addSubview(progressView)
self.arrayOfProgrssView.append(progressView)
As you can see in gif at starting point tintColor alpha is little bit less but when it tense to reach at 100% it is fully red.
I also tried with below code:-
progressView.progressTintColor = .red
but did not get expected result.
To perform animation,
DispatchQueue.main.asyncAfter(deadline: .now() + 0.001) {
UIView.animate(withDuration: self.animationInMS) {
progressView.setProgress(1, animated: true)
}
}
progressView.layoutIfNeeded()
Issue in iOS 15:-
As you see below result with other colour.
Note:- I have checked in iOS 12.4 it's working properly as you can see into image.
Please let me know is anything require from my side.
Thanks in advance
This does appear to be "new behavior" where the alpha value matches the percent completion -- although, after some quick searching I haven't found any documentation on it.
One option as a work-around: set the .progressImage instead of the tint color.
So, use your favorite code to generate a solid-color image, such as:
extension UIImage {
public static func withColor(_ color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let image = UIGraphicsImageRenderer(size: size, format: format).image { rendererContext in
color.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
return image
}
}
Then, instead of:
progressView.tintColor = .red
use:
let img = UIImage.withColor(.red)
progressView.progressImage = img
Not fully tested, but to avoid the need to change existing code, you might also try:
extension UIProgressView {
open override var tintColor: UIColor! {
didSet {
let img = UIImage.withColor(tintColor)
progressImage = img
}
}
}
Now you can keep your existing progressView.tintColor = .red

Change background color of UITabBarItem in Swift [duplicate]

This question already has answers here:
UITabBar change background color of one UITabBarItem on iOS7
(6 answers)
Closed 5 years ago.
I just want to change the background colour of one of the tab bat items. I found many links but didn't get any help from that.
Requirement:
And, this is the way I setup my tab bar items
let myTabBarItem3 = (self.tabBar.items?[2])! as UITabBarItem
myTabBarItem3.image = UIImage(named: "ic_center")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
myTabBarItem3.selectedImage = UIImage(named: "ic_center")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
What I want is the black colour background for centre tab bar item.
Any idea?
And yes it is not a duplicate, Because the previous answered are not accurate and to add extra subview is never a good option, So expecting some good solution from friends
If you want to change the background colour of only centre tabBarItem you can follow below code.
NOTE: All the below code is used in a custom class which extends UITabBarController as:
class tabbarVCViewController: UITabBarController, UITabBarControllerDelegate {
// MARK: - ViewController Override Methods.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupInitilView()
}
// MARK: - setup Initial View Methode.
private func setupInitilView() {
delegate = self
// Sets the default color of the icon of the selected UITabBarItem and Title
UITabBar.appearance().tintColor = UIColor.white
// Sets the default color of the background of the UITabBar
UITabBar.appearance().barTintColor = UIColor.white
// Sets the background color of the selected UITabBarItem (using and plain colored UIImage with the width = 1/5 of the tabBar (if you have 5 items) and the height of the tabBar)
//UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(color: UIColor.black, size: CGSize.init(width: tabBar.frame.width/4, height: tabBar.frame.height))
// Uses the original colors for your images, so they aren't not rendered as grey automatically.
for item in self.tabBar.items! {
if let image = item.image {
//item.image = image.withRenderingMode(.alwaysTemplate)
item.image = image.withRenderingMode(.alwaysOriginal) //Use default image colour as grey colour and your centre image default colour as white colour as your requirement.
}
}
//Change the backgound colour of specific tabBarItem.
let itemIndex:CGFloat = 2.0
let bgColor = UIColor.black
let itemWidth = tabBar.frame.width / CGFloat(tabBar.items!.count)
let bgView = UIView(frame: CGRect.init(x: itemWidth * itemIndex, y: 0, width: itemWidth, height: tabBar.frame.height))
bgView.backgroundColor = bgColor
tabBar.insertSubview(bgView, at: 0)
}
// MARK: - UITabbarController Override Methods .
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
}
// MARK: - UITabBarControllerDelegate Methods
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
return true
}
}
Use tabBarItem images default colour as grey according to your UI and centre tabBarItem image default colour as white colour in Asset.
And you will want to extend the UIImage class to make the plain colored image with the size you need:
extension UIImage {
func makeImageWithColorAndSize(color: UIColor, size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(CGRect.init(x: 0, y: 0, width: size.width, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
You can add a subview to the parent tabBar
Then you can set a background color on the subview.
Calculating the offset and width of your tabBarItem and inserting the subView under it.
let itemIndex = 2
let bgColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1.0)
let itemWidth = tabBar.frame.width / CGFloat(tabBar.items!.count)
let bgView = UIView(frame: CGRectMake(itemWidth * itemIndex, 0, itemWidth, tabBar.frame.height))
bgView.backgroundColor = bgColor
tabBar.insertSubview(bgView, atIndex: 0)
Try this :
UITabBar.appearance().tintColor = UIColor.pink
UITabBar.appearance().barTintColor = UIColor.white
if #available(iOS 10.0, *) {
UITabBar.appearance().unselectedItemTintColor = UIColor.white
} else {
// Fallback on earlier versions
}
let x = Double(UIScreen.main.bounds.width / 5.0)
let y = Double(tabBarController!.tabBar.frame.size.height)
let indicatorBackground: UIImage? = self.image(from: UIColor.black, for: CGSize(width: x, height: y))
UITabBar.appearance().selectionIndicatorImage = indicatorBackground
Helper Methods
func image(from color: UIColor, for size: CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
autoreleasepool {
UIGraphicsBeginImageContext(rect.size)
}
let context: CGContext? = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
You can use imageView to achieve this affect , try this approach
let myImageView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
// Now add this imageView as subview and apply constraints
tabbar.addSubview(myImageView)
myImageView.translatesAutoresizingMaskIntoConstraints = false
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[v0(28)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": myImageView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[v0(28)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": myImageView]))
tabbar.myImageView.image = UIImage(named: "ic_center")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
tabbar.myImageView.tintColor = UIColor.black

Swift 3 - full width of UITabBarItem for selectionIndicatorImage

i have a UITabBar with three tabs. Now I want to assign or lets say to fill the complete width of one tab to the related selectionIndicatorImage cause currently I got a border if a tab is selected. Like the tab on the left side shows in the following screenshot:
I made a subclass of UITabBar with a new property:
var activeItemBackground:UIColor = UIColor.white {
didSet {
let numberOfItems = CGFloat((items!.count))
let tabBarItemSize = CGSize(width: frame.width / numberOfItems,
height: frame.height)
selectionIndicatorImage = UIImage.imageWithColor(color: activeItemBackground,
size: tabBarItemSize).resizableImage(withCapInsets: .zero)
frame.size.width = frame.width + 4
frame.origin.x = -2
}
}
And the UIImage-Extension in order to have backgroundColor and an image:
extension UIImage
{
class func imageWithColor(color: UIColor, size: CGSize) -> UIImage
{
let rect: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
I read much stuff about this problem but unfortunately I can't get it to work. Is something missing in my code?
I think you're taking a couple extra steps...
You are calculating the exact size of the tab bar item, and creating an image of that size, so you shouldn't need the .resizableImage part.
And, since you are setting to exact size, you also shouldn't need to resize the tab bar frame.
This appears to work fine in my testing (using your .imageWithColor func):
class MyTabBar: UITabBar {
var activeItemBackground:UIColor = UIColor.white {
didSet {
let numberOfItems = CGFloat((items!.count))
let tabBarItemSize = CGSize(width: frame.width / numberOfItems,
height: frame.height)
selectionIndicatorImage = UIImage.imageWithColor(color: activeItemBackground,
size: tabBarItemSize)
}
}
}
Then in viewDidLoad of the first VC:
if let tb = self.tabBarController?.tabBar as? MyTabBar {
tb.activeItemBackground = UIColor.red
}

Change navigation bar bottom border color Swift

It works with
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = UIColor.redColor().as1ptImage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension UIColor {
func as1ptImage() -> UIImage {
UIGraphicsBeginImageContext(CGSizeMake(1, 1))
let ctx = UIGraphicsGetCurrentContext()
self.setFill()
CGContextFillRect(ctx, CGRect(x: 0, y: 0, width: 1, height: 1))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
But when I add a UITableView it doesn't appear on it and when I add a UISearchView it appears but removes the navigation bar.
Anyone knows how to solve this?
You have to adjust the shadowImage property of the navigation bar.
Try this one. I created a category on UIColor as an helper, but you can refactor the way you prefer.
extension UIColor {
func as1ptImage() -> UIImage {
UIGraphicsBeginImageContext(CGSizeMake(1, 1))
let ctx = UIGraphicsGetCurrentContext()
self.setFill()
CGContextFillRect(ctx, CGRect(x: 0, y: 0, width: 1, height: 1))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Option 1: on a single navigation bar
And then in your view controller (change the UIColor to what you like):
// We can use a 1px image with the color we want for the shadow image
self.navigationController?.navigationBar.shadowImage = UIColor.redColor().as1ptImage()
// We need to replace the navigation bar's background image as well
// in order to make the shadowImage appear. We use the same 1px color tecnique
self.navigationController?.navigationBar.setBackgroundImage(UIColor.yellowColor‌​().as1ptImage(), forBarMetrics: .Default)
Option 2: using appearance proxy, on all navigation bars
Instead of setting the background image and shadow image on each navigation bar, it is possible to rely on UIAppearance proxy. You could try to add those lines to your AppDelegate, instead of adding the previous ones in the viewDidLoad.
// We can use a 1px image with the color we want for the shadow image
UINavigationBar.appearance().shadowImage = UIColor.redColor().as1ptImage()
// We need to replace the navigation bar's background image as well
// in order to make the shadowImage appear. We use the same 1px color technique
UINavigationBar.appearance().setBackgroundImage(UIColor.yellowColor().as1ptImage(), forBarMetrics: .Default)
Wonderful contributions from #TheoF, #Alessandro and #Pavel.
Here is what I did for...
Swift 4
extension UIColor {
/// Converts this `UIColor` instance to a 1x1 `UIImage` instance and returns it.
///
/// - Returns: `self` as a 1x1 `UIImage`.
func as1ptImage() -> UIImage {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
setFill()
UIGraphicsGetCurrentContext()?.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
return image
}
}
Using it in viewDidLoad():
/* In this example, I have a ViewController embedded in a NavigationController in IB. */
// Remove the background color.
navigationController?.navigationBar.setBackgroundImage(UIColor.clear.as1ptImage(), for: .default)
// Set the shadow color.
navigationController?.navigationBar.shadowImage = UIColor.gray.as1ptImage()
Putting #alessandro-orru's answer in one extension
extension UINavigationController {
func setNavigationBarBorderColor(_ color:UIColor) {
self.navigationBar.shadowImage = color.as1ptImage()
}
}
extension UIColor {
/// Converts this `UIColor` instance to a 1x1 `UIImage` instance and returns it.
///
/// - Returns: `self` as a 1x1 `UIImage`.
func as1ptImage() -> UIImage {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
setFill()
UIGraphicsGetCurrentContext()?.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
return image
}
}
then in your view controller just add:
self.navigationController?.setNavigationBarBorderColor(UIColor.red)
From iOS 13 on, you can use the UINavigationBarAppearance() class with the shadowColor property:
if #available(iOS 13.0, *) {
let style = UINavigationBarAppearance()
style.shadowColor = UIColor.clear // Effectively removes the border
navigationController?.navigationBar.standardAppearance = style
// Optional info for follow-ups:
// The above will override other navigation bar properties so you may have to assign them here, for example:
//style.buttonAppearance.normal.titleTextAttributes = [.font: UIFont(name: "YourFontName", size: 17)!]
//style.backgroundColor = UIColor.orange
//style.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "AnotherFontName", size: 20.0)!]
} else {
// Fallback on earlier versions
}
Solution for Swift 4.0 - 5.2
Here is small extension for changing both Height and Color of bottom navbar line
extension UINavigationController
{
func addCustomBottomLine(color:UIColor,height:Double)
{
//Hiding Default Line and Shadow
navigationBar.setValue(true, forKey: "hidesShadow")
//Creating New line
let lineView = UIView(frame: CGRect(x: 0, y: 0, width:0, height: height))
lineView.backgroundColor = color
navigationBar.addSubview(lineView)
lineView.translatesAutoresizingMaskIntoConstraints = false
lineView.widthAnchor.constraint(equalTo: navigationBar.widthAnchor).isActive = true
lineView.heightAnchor.constraint(equalToConstant: CGFloat(height)).isActive = true
lineView.centerXAnchor.constraint(equalTo: navigationBar.centerXAnchor).isActive = true
lineView.topAnchor.constraint(equalTo: navigationBar.bottomAnchor).isActive = true
}
}
And after adding this extension, you can call this method on any UINavigationController (e.g. from ViewController viewDidLoad())
self.navigationController?.addCustomBottomLine(color: UIColor.black, height: 20)
For iOS 13 and later
guard let navigationBar = navigationController?.navigationBar else { return }
navigationBar.isTranslucent = true
if #available(iOS 13.0, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.backgroundImage = UIImage()
appearance.backgroundColor = .clear
navigationBar.standardAppearance = appearance
} else {
navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationBar.shadowImage = UIImage()
}
for Swift 3.0 just change this line:
CGContextFillRect(ctx, CGRect(x: 0, y: 0, width: 1, height: 1))
to this:
ctx?.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
There's a much better option available these days:
UINavigationBar.appearance().shadowImage = UIImage()

Remove tab bar item text, show only image

Simple question, how can I remove the tab bar item text and show only the image?
I want the bar items to like in the instagram app:
In the inspector in xcode 6 I remove the title and choose a #2x (50px) and a #3x (75px) image. However the image does not use the free space of the removed text. Any ideas how to achieve the same tab bar item image like in the instagram app?
You should play with imageInsets property of UITabBarItem. Here is sample code:
let tabBarItem = UITabBarItem(title: nil, image: UIImage(named: "more")
tabBarItem.imageInsets = UIEdgeInsets(top: 9, left: 0, bottom: -9, right: 0)
Values inside UIEdgeInsets depend on your image size. Here is the result of that code in my app:
// Remove the titles and adjust the inset to account for missing title
for(UITabBarItem * tabBarItem in self.tabBar.items){
tabBarItem.title = #"";
tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
}
Here is how you do it in a storyboard.
Clear the title text, and set the image inset like the screenshot below
Remember the icon size should follow the apple design guideline
This means you should have 25px x 25px for #1x, 50px x 50px for #2x, 75px x 75px for #3x
Using approach with setting each UITabBarItems title property to ""
and update imageInsets won't work properly if in view controller self.title is set. For example if self.viewControllers of UITabBarController are embedded in UINavigationController and you need title to be displayed on navigation bar. In this case set UINavigationItems title directly using self.navigationItem.title, not self.title.
If you're using storyboards this would be you best option. It loops through all of the tab bar items and for each one it sets the title to nothing and makes the image full screen. (You must have added an image in the storyboard)
for tabBarItem in tabBar.items!
{
tabBarItem.title = ""
tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0)
}
Swift version of ddiego answer
Compatible with iOS 11
Call this function in viewDidLoad of every first child of the viewControllers after setting title of the viewController
Best Practice:
Alternativelly as #daspianist suggested in comments
Make a subclass of like this class BaseTabBarController:
UITabBarController, UITabBarControllerDelegate and put this function
in the subclass's viewDidLoad
func removeTabbarItemsText() {
var offset: CGFloat = 6.0
if #available(iOS 11.0, *), traitCollection.horizontalSizeClass == .regular {
offset = 0.0
}
if let items = tabBar.items {
for item in items {
item.title = ""
item.imageInsets = UIEdgeInsets(top: offset, left: 0, bottom: -offset, right: 0)
}
}
}
iOS 11 throws a kink in many of these solutions, so I just fixed my issues on iOS 11 by subclassing UITabBar and overriding layoutSubviews.
class MainTabBar: UITabBar {
override func layoutSubviews() {
super.layoutSubviews()
// iOS 11: puts the titles to the right of image for horizontal size class regular. Only want offset when compact.
// iOS 9 & 10: always puts titles under the image. Always want offset.
var verticalOffset: CGFloat = 6.0
if #available(iOS 11.0, *), traitCollection.horizontalSizeClass == .regular {
verticalOffset = 0.0
}
let imageInset = UIEdgeInsets(
top: verticalOffset,
left: 0.0,
bottom: -verticalOffset,
right: 0.0
)
for tabBarItem in items ?? [] {
tabBarItem.title = ""
tabBarItem.imageInsets = imageInset
}
}
}
I used the following code in my BaseTabBarController's viewDidLoad.
Note that in my example, I have 5 tabs, and selected image will always be base_image + "_selected".
// Get tab bar and set base styles
let tabBar = self.tabBar;
tabBar.backgroundColor = UIColor.whiteColor()
// Without this, images can extend off top of tab bar
tabBar.clipsToBounds = true
// For each tab item..
let tabBarItems = tabBar.items?.count ?? 0
for i in 0 ..< tabBarItems {
let tabBarItem = tabBar.items?[i] as UITabBarItem
// Adjust tab images (Like mstysf says, these values will vary)
tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -6, 0);
// Let's find and set the icon's default and selected states
// (use your own image names here)
var imageName = ""
switch (i) {
case 0: imageName = "tab_item_feature_1"
case 1: imageName = "tab_item_feature_2"
case 2: imageName = "tab_item_feature_3"
case 3: imageName = "tab_item_feature_4"
case 4: imageName = "tab_item_feature_5"
default: break
}
tabBarItem.image = UIImage(named:imageName)!.imageWithRenderingMode(.AlwaysOriginal)
tabBarItem.selectedImage = UIImage(named:imageName + "_selected")!.imageWithRenderingMode(.AlwaysOriginal)
}
Swift 4 approach
I was able to do the trick by implementing a function that takes a TabBarItem and does some formatting to it.
Moves the image a little down to make it be more centered and also hides the text of the Tab Bar.
Worked better than just setting its title to an empty string, because when you have a NavigationBar as well, the TabBar regains the title of the viewController when selected
func formatTabBarItem(tabBarItem: UITabBarItem){
tabBarItem.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.clear], for: .selected)
tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.clear], for: .normal)
}
Latest syntax
extension UITabBarItem {
func setImageOnly(){
imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.clear], for: .selected)
setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.clear], for: .normal)
}
}
And just use it in your tabBar as:
tabBarItem.setImageOnly()
Here is a better, more foolproof way to do this other than the top answer:
[[UITabBarItem appearance] setTitleTextAttributes:#{NSForegroundColorAttributeName: [UIColor clearColor]}
forState:UIControlStateNormal];
[[UITabBarItem appearance] setTitleTextAttributes:#{NSForegroundColorAttributeName: [UIColor clearColor]}
forState:UIControlStateHighlighted];
Put this in your AppDelegate.didFinishLaunchingWithOptions so that it affects all tab bar buttons throughout the life of your app.
A minimal, safe UITabBarController extension in Swift (based on #korgx9 answer):
extension UITabBarController {
func removeTabbarItemsText() {
tabBar.items?.forEach {
$0.title = ""
$0.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
}
}
}
Based on the answer of ddiego, in Swift 4.2:
extension UITabBarController {
func cleanTitles() {
guard let items = self.tabBar.items else {
return
}
for item in items {
item.title = ""
item.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
}
}
}
And you just need to call self.tabBarController?.cleanTitles() in your view controller.
Custom TabBar - iOS 13, Swift 5, XCode 11
TabBar items without text
TabBar items centered vertically
Rounded TabBar view
TabBar Dynamic position and frames
Storyboard based. It can be achieved easily programmatically too. Only 4 Steps to follow:
Tab Bar Icons must be in 3 sizes, in black color. Usually, I download from fa2png.io - sizes: 25x25, 50x50, 75x75. PDF image files do not work!
In Storyboard for the tab bar item set the icon you want to use through Attributes Inspector. (see screenshot)
Custom TabBarController -> New File -> Type: UITabBarController -> Set on storyboard. (see screenshot)
UITabBarController class
class RoundedTabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Custom tab bar view
customizeTabBarView()
}
private func customizeTabBarView() {
let tabBarHeight = tabBar.frame.size.height
self.tabBar.layer.masksToBounds = true
self.tabBar.isTranslucent = true
self.tabBar.barStyle = .default
self.tabBar.layer.cornerRadius = tabBarHeight/2
self.tabBar.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner]
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let viewWidth = self.view.bounds.width
let leadingTrailingSpace = viewWidth * 0.05
tabBar.frame = CGRect(x: leadingTrailingSpace, y: 200, width: viewWidth - (2 * leadingTrailingSpace), height: 49)
}
}
Result
code:
private func removeText() {
if let items = yourTabBarVC?.tabBar.items {
for item in items {
item.title = ""
}
}
}
In my case, same ViewController was used in TabBar and other navigation flow. Inside my ViewController, I have set self.title = "Some Title" which was appearing in TabBar regardless of setting title nil or blank while adding it in tab bar. I have also set imageInsets as follow:
item.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
So inside my ViewController, I have handled navigation title as follow:
if isFromTabBar {
// Title for NavigationBar when ViewController is added in TabBar
// NOTE: Do not set self.title = "Some Title" here as it will set title of tabBarItem
self.navigationItem.title = "Some Title"
} else {
// Title for NavigationBar when ViewController is opened from navigation flow
self.title = "Some Title"
}
Based on all the great answers on this page, I've crafted another solution that also allows you to show the the title again. Instead of removing the content of title, I just change the font color to transparent.
extension UITabBarItem {
func setTitleColorFor(normalState: UIColor, selectedState: UIColor) {
self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: normalState], for: .normal)
self.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: selectedState], for: .selected)
}
}
extension UITabBarController {
func hideItemsTitle() {
guard let items = self.tabBar.items else {
return
}
for item in items {
item.setTitleColorFor(normalState: UIColor(white: 0, alpha: 0), selectedState: UIColor(white: 0, alpha: 0))
item.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
}
}
func showItemsTitle() {
guard let items = self.tabBar.items else {
return
}
for item in items {
item.setTitleColorFor(normalState: .black, selectedState: .yellow)
item.imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
}
Easiest way and always works:
class TabBar: UITabBar {
override func layoutSubviews() {
super.layoutSubviews()
subviews.forEach { subview in
if subview is UIControl {
subview.subviews.forEach {
if $0 is UILabel {
$0.isHidden = true
subview.frame.origin.y = $0.frame.height / 2.0
}
}
}
}
}
}
make a subclass of UITabBarController and assign that to your tabBar , then in the viewDidLoad method place this line of code:
tabBar.items?.forEach({ (item) in
item.imageInsets = UIEdgeInsets.init(top: 8, left: 0, bottom: -8, right: 0)
})
If you are looking to center the tabs / change the image insets without using magic numbers, the following has worked for me (in Swift 5.2.2):
In a UITabBarController subclass, you can add add the image insets after setting the view controllers.
override var viewControllers: [UIViewController]? {
didSet {
addImageInsets()
}
}
func addImageInsets() {
let tabBarHeight = tabBar.frame.height
for item in tabBar.items ?? [] where item.image != nil {
let imageHeight = item.image?.size.height ?? 0
let inset = CGFloat(Int((tabBarHeight - imageHeight) / 4))
item.imageInsets = UIEdgeInsets(top: inset,
left: 0,
bottom: -inset,
right: 0)
}
}
Several of the options above list solutions for dealing with hiding the text.

Resources