Add a line as a selection indicator to a UITabbarItem in Swift

后端 未结 4 1548
走了就别回头了
走了就别回头了 2020-12-09 19:18

I wanna use a thick line at the bottom of a UITabbarItems as a selection indicator. Due to the fact that the App must work on different phone sizes, I cannot use a image as

4条回答
  •  借酒劲吻你
    2020-12-09 19:59

    I solved my problem.

    Features of this tiny code snippet:

    • width is dynamic
    • it is animated
    • it is a lot more customizable for future features

      class FirstViewController: UIViewController {
      
      let rectShape = CAShapeLayer()
      let indicatorHeight: CGFloat = 5
      var indicatorWidth: CGFloat!
      let indicatorBottomMargin: CGFloat = 2
      let indicatorLeftMargin: CGFloat = 2
      
      override func viewDidLoad() {
          super.viewDidLoad()
      
          // setup tabbar indicator
          rectShape.fillColor = UIColor.redColor().CGColor
          indicatorWidth = view.bounds.maxX / 2 // count of items
          self.tabBarController!.view.layer.addSublayer(rectShape)
          self.tabBarController?.delegate = self
      
          // initial position
          updateTabbarIndicatorBySelectedTabIndex(0)
      }
      
      func updateTabbarIndicatorBySelectedTabIndex(index: Int) -> Void
      {
          let updatedBounds = CGRect( x: CGFloat(index) * (indicatorWidth + indicatorLeftMargin),
                                      y: view.bounds.maxY - indicatorHeight,
                                      width: indicatorWidth - indicatorLeftMargin,
                                      height: indicatorHeight)
      
          let path = CGPathCreateMutable()
          CGPathAddRect(path, nil, updatedBounds)
          rectShape.path = path
      }
      }
      
      extension FirstViewController: UITabBarControllerDelegate {
      
      func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
          updateTabbarIndicatorBySelectedTabIndex(tabBarController.selectedIndex)
      }
      }
      

提交回复
热议问题