在Swift for iOS中将TabBarItem标题字体更改为粗体

时间:2015-07-13 16:29:26

标签: ios swift uikit

我尝试将所选标签栏项的字体粗细设置为粗体字。它似乎没有效果。知道什么是错的。 forState: .Normal按预期工作,forState: .Selected无效。

let tabBarItem0 = tabBar.items![0] as! UITabBarItem
var selectedImage0 : UIImage = UIImage(named:"ic_tabbar_item_one")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
var fontLight:UIFont = UIFont(name: "HelveticaNeue-UltraLight", size: 12)!
var fontBold:UIFont = UIFont(name: "HelveticaNeue-Bold", size: 12)!

tabBarItem0.image = unselectedImage0
tabBarItem0.selectedImage = selectedImage0
tabBarItem0.title = "Overview"
tabBarItem0.setTitleTextAttributes(
    [
        NSForegroundColorAttributeName: UIColor.whiteColor(),
        NSFontAttributeName: fontLight
    ], forState: .Normal)

tabBarItem0.setTitleTextAttributes(
    [
        NSForegroundColorAttributeName: UIColor.whiteColor(),
        NSFontAttributeName: fontBold
    ], forState: UIControlState.Selected)

6 个答案:

答案 0 :(得分:3)

找到解决方案(Swift 3,XCode 8.1)

  1. 在Storyboard中,为每个UITabBarItem提供一个唯一标记:对于每个标签 - >选择它并转到它"属性检查器" - >在"标记"中为每个人提供唯一号码。字段,但你不应该使用零(我使用1到4)。

    这将我们设置为稍后,以确定按下哪个标签。

    1. 创建UITabBarController的新子类,然后分配:FILE - >新文件 - > iOS Cocoa Touch - >创建UITabBarController的子类。将新的.swift文件分配给您的.swift文件 " Identity Inspector下的UITabBarController。"

      我们需要在UITabBarController中使用自定义逻辑。

      1. 创建UITabBarItem的新子类,将相同的文件分配给所有UITabBarItems :FILE - >新文件 - > iOS Cocoa Touch - >创建UITabBarItem的子类,并将相同的子类分配给所有选项卡。

        我们的标签栏项目需要共享自定义逻辑。

        1. 将此代码添加到您的UITabBarItem子类,它会设置初始状态(主要标签粗体,其余未选中),并允许进行程序化标签更改:

          class MyUITabBarItemSubclass: UITabBarItem {
          
              //choose initial state fonts and weights here
              let normalTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular) 
              let selectedTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightBold)
          
              //choose initial state colors here
              let normalTitleColor = UIColor.gray 
              let selectedTitleColor = UIColor.black
          
              //assigns the proper initial state logic when each tab instantiates 
              override func awakeFromNib() {
                  super.awakeFromNib()
          
                  //this tag # should be your primary tab's Tag* 
                  if self.tag == 1 { 
                      self.setTitleTextAttributes([NSFontAttributeName: selectedTitleFont, NSForegroundColorAttributeName: selectedTitleColor], for: UIControlState.normal)
                  } else {
                      self.setTitleTextAttributes([NSFontAttributeName: normalTitleFont, NSForegroundColorAttributeName: normalTitleColor], for: UIControlState.normal)
                  }
          
              }
          
          }
          
        2. 在这里我们设置初始状态,以便在应用程序打开时正确设置选项卡,我们将在下一个子类中处理物理选项卡。

          1. 将此代码添加到您的UITabBarController子类,这是在按下选项卡时分配正确状态的逻辑。

            class MyUITabBarControllerSubclass: UITabBarController {
            
                //choose normal and selected fonts here
                let normalTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular)
                let selectedTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightBold)
            
                //choose normal and selected colors here
                let normalTitleColor = UIColor.gray
                let selectedTitleColor = UIColor.black
            
            
                //the following is a delegate method from the UITabBar protocol that's available 
                //to UITabBarController automatically. It sends us information every
                //time a tab is pressed. Since we Tagged our tabs earlier, we'll know which one was pressed,
                //and pass that identifier into a function to set our button states for us
            
                override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
                    setButtonStates(itemTag: item.tag)
                }
            
            
                //the function takes the tabBar.tag as an Int
                func setButtonStates (itemTag: Int) {
            
                    //making an array of all the tabs
                    let tabs = self.tabBar.items
            
                    //looping through and setting the states
                    var x = 0
                    while x < (tabs?.count)! {
            
                        if tabs?[x].tag == itemTag {
                            tabs?[x].setTitleTextAttributes([NSFontAttributeName: selectedTitleFont, NSForegroundColorAttributeName: selectedTitleColor], for: UIControlState.normal)
                        } else {
                            tabs?[x].setTitleTextAttributes([NSFontAttributeName: normalTitleFont, NSForegroundColorAttributeName: normalTitleColor], for: UIControlState.normal)
                        }
            
                        x += 1
            
                    }
            
                }
            
            }
            
          2. 看起来这是一种痛苦,因为由于某种原因,标签不会将状态变化识别为&#34; .Selected&#34;。我们必须通过仅使用.Normal状态来做所有事情 - 基本上自己检测状态变化。

            1. 您可以通过编程方式更改标签并仍然可以通过...检测状态更改。如果有人有兴趣,我稍后会更新,只需询问。
            2. 希望这有帮助!

答案 1 :(得分:1)

问题是tabBarItem0的状态未更改为Selected。因为这是UITabBarItem,它代表UITabBar的单个元素。因此,您无法使用UITabBarItem API直接更改状态。您必须通过分配selectedItem来更改状态。

这些信息来自文档,我建议所有程序员都有这样的技能。希望这会有所帮助。

答案 2 :(得分:1)

UITabBarItem.appearance().setTitleTextAttributes(
        [NSFontAttributeName: UIFont(name:"your_font_name", size:11)!, 
            NSForegroundColorAttributeName: UIColor(rgb: 0x929292)], 
        forState: .Normal)

答案 3 :(得分:0)

要设置TitleTextAttribute,您应该使用appearance代理,例如:[UIBarItem appearance]

答案 4 :(得分:0)

构建设置\快速语言版本:4.1

常规\部署目标:10.3

import UIKit

class FirstViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    let attrsNormal = [NSAttributedStringKey.foregroundColor : UIColor.black,
                 NSAttributedStringKey.font : UIFont(name: "Arial", size: 14)!]
    UITabBarItem.appearance().setTitleTextAttributes(attrsNormal,
                                                     for: UIControlState.normal)

    let attrsSelected = [NSAttributedStringKey.foregroundColor : UIColor.red,
                       NSAttributedStringKey.font : UIFont(name: "Arial", size: 14)!]
    UITabBarItem.appearance().setTitleTextAttributes(attrsSelected,
                                                     for: UIControlState.selected)
  }
  ...
}

答案 5 :(得分:0)

当我尝试使用 UITabBarItem 更改所选选项卡的字体但它不起作用时。建议采用委托以在选项卡更改时获得通知。我只是拼凑起来。


private class MyTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
    }

    override func setViewControllers(_ viewControllers: [UIViewController]?, animated: Bool) {
        super.setViewControllers(viewControllers, animated: animated)
        changeFontSelectedTab()
    }
}

extension MyTabBarController: UITabBarControllerDelegate {

    public func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        changeFontSelectedTab()
    }

    func changeFontSelectedTab() {
        let normalLabelFont = UIFont.systemFont(ofSize: 18, weight: .regular)
        let selectedLabelFont = UIFont.systemFont(ofSize: 20, weight: .semibold)
        let labelColor = UIColor.init(red: 38/255.0, green: 38/255.0, blue: 38/255.0, alpha: 1.0)
        let selectedIconColor = UIColor.init(red: 8/255.0, green: 8/255.0, blue: 8/255.0, alpha: 1.0)

        viewControllers?.forEach {
            let selected = $0 == self.selectedViewController
            if selected {
                $0.tabBarController?.tabBar.tintColor = selectedIconColor
            }
            let selectFont =  (selected ? selectedLabelFont : normalLabelFont)
            $0.tabBarItem.setTitleTextAttributes([.font: selectFont, .foregroundColor: labelColor], for: .normal)
        }
    }
}