Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing tab bar font in Swift

I have been trying to change the font for the tab bar items however I haven't been able to find any Swift examples. I know that this is how you change it in Objective-C:

[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont, nil] forState:UIControlStateNormal]; 

But how can I translate this into Swift?

like image 920
user3746428 Avatar asked Sep 26 '14 22:09

user3746428


People also ask

How do I create a custom tab bar in Swift?

Implement a view controller that can hold some other view controllers. Show one of those view controllers. Show a tab bar at the bottom of the screen over the shown view controller. Switch between the various view controllers when the user taps on a tab bar button.


2 Answers

The UITextAttributeFont was deprecated in iOS 7. You should use the NS variant instead:

import UIKit  let appearance = UITabBarItem.appearance() let attributes = [NSFontAttributeName:UIFont(name: "American Typewriter", size: 20)] appearance.setTitleTextAttributes(attributes, forState: .Normal) 
like image 153
AlBlue Avatar answered Sep 20 '22 02:09

AlBlue


Swift 4.2

UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "FontName", size: 10)!], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "FontName", size: 10)!], for: .selected) 

Swift 4

UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "FontName", size: 10)!], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "FontName", size: 10)!], for: .selected) 

Swift 3

UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Font-Name", size: 10)!], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Font-Name", size: 10)!], for: .selected) 

Note: Use setTitleTextAttributes for both .normal and .selected to have changes persist selection state changes.

like image 44
iOS.Lover Avatar answered Sep 21 '22 02:09

iOS.Lover