ios - 自定义 UITabBarController - DidSelect/AnyCustomization 委托(delegate)问题

标签 ios swift uitabbarcontroller tabbar

我创建了自定义 TabBar 类,但我遇到了一些问题,例如,当选项卡隐藏时,如何从此类调用任何函数? (我想在隐藏标签栏时隐藏我的条纹)另外,当我使用 tabBarController?.selectedIndex = 3 时,委托(delegate) didSelect 未被调用,我该如何解决它?这是我的简单代码。感谢您的帮助

class customTabBar: UITabBarController {


var stripe = UIView()

override func viewDidLoad() {
    super.viewDidLoad()

    let cellWidth = tabBar.frame.width/5
    stripe = UIView(frame: CGRect(x: 0, y: tabBar.frame.minY + 20, width: (tabBar.frame.width/5) * 0.6, height: 6))
    stripe.center.x = cellWidth/2
    stripe.applyGradient(colours: [UIColor.init(hexFromString: "5897ee"),UIColor.init(hexFromString: "5228d8")])
    stripe.layer.cornerRadius = 2
    stripe.layer.masksToBounds = true
    self.view.addSubview(stripe)

}

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

    let index: Int = item.tag + 1
    let cellWidth = tabBar.frame.width/5
    let newPostion = cellWidth * CGFloat(index)

    UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.3, options: .curveEaseInOut, animations: {

        self.stripe.center.x = newPostion - (cellWidth/2)

    })
}

}

最佳答案

class MyTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //Add the stripe to tabBar,so it will hidden when tabBar hidden
        let cellWidth = tabBar.frame.width/5
        let stripe = UIView(frame: CGRect(x: 0, y: tabBar.frame.minY + 20, width: (tabBar.frame.width/5) * 0.6, height: 6))
        stripe.center.x = cellWidth/2
        stripe.layer.cornerRadius = 2
        stripe.layer.masksToBounds = true
        self.tabBar.addSubview(stripe)

    }

    //use this to observe tabBarController?.selectedIndex = 3
    override var selectedIndex: Int{
        didSet{
            //do what you want
        }
    }
}

extension UIViewController {

    //use this to call get MyTabBarController instance and call any function
    var myTabBarcontroller : MyTabBarController?{
        get{
            return self.tabBarController as? MyTabBarController
        }
    }
}

关于ios - 自定义 UITabBarController - DidSelect/AnyCustomization 委托(delegate)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58352266/

相关文章:

ios - 允许一次调用一个类别方法 ios (@synchronized)

ios - NSDictionary 根本没有数据

ios - 如何在 Core Data 中保存用户偏好?

ios - 标签栏在 segue 上消失

swift - 通过 TabbarController 和 NavigationController 进行导航。如何?

uitabbarcontroller - UITabBarDelegate 还是 UITabBarControllerDelegate?

ios - 如果顶级 UIView 没有收到它想要处理的手势,将手势/触摸传递给另一个 UIView?

ios - 检索要标记的 Firebase 数据

iOS - 同时发送和接收数据

ios - UITableView 分隔线被添加到节标题 View ,怎么办?