Search code examples
swiftfontsios9uitabbaritem

Customizing text color AND font of UITabBarItem causing weird result in swift


I am trying to change the text of my UITabBarItems and have used questions such as this. The second answer works great for me unless I try to adjust the font of the UITabBarItem. This snippet produces the expected results of the selected text being white and the unselected item being light gray:

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor()], forState:.Normal)

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:.Selected)

enter image description here

However, if this is added :

UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName:UIFont(name: "American Typewriter", size: 13)!], forState: .Selected)

enter image description here

For some reason the text becomes black when it is both selected and unselected and the font remains unchanged.

Weirdly enough if I change .Selected to .Normal in the last snippet, then the selected text turns white and the text is made to match the font in the code.

enter image description here

UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName:UIFont(name: "American Typewriter", size: 13)!], forState: .Normal)

This is almost perfect however the unselected text is now unchanged. Im not sure if I am doing something wrong or this is a bug, but if there are any other methods to completing this task, I would love to hear it.

Based on dfri's comments I have tried this:

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor(),
        NSFontAttributeName : [NSFontAttributeName:UIFont(name: "American Typewriter", size: 13)!]], forState:.Selected)

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.whiteColor(),
        NSFontAttributeName : [NSFontAttributeName:UIFont(name: "American Typewriter", size: 13)!]], forState:.Normal)

and now the app is crashing. The error says :

unrecognized selector sent to instance 0x7fa6d9461ef0

which does not make any sense to me


Solution

  • Try the following

    let colorNormal : UIColor = UIColor.blackColor()
    let colorSelected : UIColor = UIColor.whiteColor()
    let titleFontAll : UIFont = UIFont(name: "American Typewriter", size: 13.0)!
    
    let attributesNormal = [
        NSForegroundColorAttributeName : colorNormal,
        NSFontAttributeName : titleFontAll
    ]
    
    let attributesSelected = [
        NSForegroundColorAttributeName : colorSelected,
        NSFontAttributeName : titleFontAll
    ]
    
    UITabBarItem.appearance().setTitleTextAttributes(attributesNormal, forState: .Normal)
    UITabBarItem.appearance().setTitleTextAttributes(attributesSelected, forState: .Selected)