2017-01-07 23 views
3

我有一個UITabBarController子類,我想在選定的UITabBarItem圖標下添加一個白色的小長方形圖標。我使用了UIView,我將TabBarItem作爲子視圖並將視圖添加爲子視圖。我在viewWillAppear中這樣做,它顯示,但是當我選擇另一個選項卡時,它不會出現在該選項卡欄項下。 這裏是我的代碼:如何在Swift中的選定UITabBarItem圖標下面添加小圖標

let view = orderedTabBarItemViews()[selectedIndex] 

bottomIcon.frame = CGRect(x: 0, y: 42, width: 10, height: 3) 
bottomIcon.center = CGPoint(x: view.bounds.size.width/2, y: view.bounds.size.height/2) 
bottomIcon.backgroundColor = UIColor.white 
bottomIcon.layer.cornerRadius = 2 

view.addSubview(bottomIcon) 

orderedTabBarItemViews()函數獲取的TabBarItem S作爲的UIView秒的陣列。 這裏是我想要達到

回答

1

我不認爲這是一個方便的方式添加和顯示/隱藏查看圖像。

我建議你使用UIImage s來做到這一點 - 所以一個點用於選定狀態,另一個點用於未選擇狀態。

1

有幾種選擇:

  1. 添加它作爲選擇圖像的一部分。這是最簡單的解決方案。

  2. 添加其作爲標籤頁的標籤(例如,使用-字符,或者更好一些Unicode字符,例如)用大字體。

  3. 將其作爲覆蓋層添加到UITabBar

0

這是一個快速劈我使用Unicode字符創建⬬:

extension UITabBarController { 

    func addDotToTabBarItemWith(index: Int,size: CGFloat,color: UIColor, verticalOffset: CGFloat = 1.0) { 

     // set distance from tab bar icons 
     for tabItem in self.viewControllers! { 
      tabItem.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0.0, vertical: verticalOffset) 
     } 

     // set default appearance for tabbar icon title 
     UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: color,NSFontAttributeName:UIFont(name: "American Typewriter", size: size)!], for: .normal) 
     UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: color,NSFontAttributeName:UIFont(name: "American Typewriter", size: size)!], for: .selected) 

     // place the dot 
     guard let vc = self.viewControllers?[index] else { 
      log.error("Couldn't find a TabBar Controller with index:\(index)") 
      return 
     } 

     vc.tabBarItem.title = "⬬" 
    } 
} 
相關問題