在 Swift 中向 UITabbarItem 添加一行作为选择指示器 [英] Add a line as a selection indicator to a UITabbarItem in Swift

查看:34
本文介绍了在 Swift 中向 UITabbarItem 添加一行作为选择指示器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 UITabbarItems 底部使用粗线作为选择指示器.由于该应用程序必须适用于不同的手机尺寸,我无法使用图像作为选择指示符.这就是为什么我认为我必须使用 Swift 来做到这一点.(该行必须是页面宽度的 1/3).

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 selection indicator. That's why I think I have to use Swift to do this. (The line has to be 1/3 of page width).

我尝试使用 UITabBarItem.appearance() 但没有成功.

I tried to use UITabBarItem.appearance() but without success.

推荐答案

我解决了我的问题.

这个小代码片段的特点:

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)
}
}

这篇关于在 Swift 中向 UITabbarItem 添加一行作为选择指示器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆