美文网首页
Swift-TabBar选中item并通知controller

Swift-TabBar选中item并通知controller

作者: feb961880dc1 | 来源:发表于2019-12-08 14:04 被阅读0次
1.自定义CustomTabBarController,继承自UITabBarController

定义属性lastIndex,用于判断是否重复点击

class CustomTabBarController: UITabBarController {
    var lastIndex:Int = 0
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        self.delegate = self
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
2.遵循UITabBarControllerDelegate协议

通过shouldSelect方法获取上一个位置索引,其中需要判断子controller是否属于UINavigationController

extension CustomTabBarController:UITabBarControllerDelegate{
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        self.lastIndex = self.selectedIndex
        return true
    }
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        if viewController.isMember(of: UINavigationController.classForCoder()) {
            if let navi = viewController as? UINavigationController,let vc = navi.topViewController as? CYHTabBarControllerDelegate{
                vc.tabBarSelected(self.lastIndex == self.selectedIndex)
            }
        }
        else {
            if let vc = viewController as? CYHTabBarControllerDelegate{
                vc.tabBarSelected(self.lastIndex == self.selectedIndex)
            }
        }
    }
}
3.定义CustomTabBarControllerDelegate协议
protocol CustomTabBarControllerDelegate {
    func tabBarSelected(_ isRepeat:Bool)
}
4.目标controller遵循CustomTabBarControllerDelegate协议: MainController.swift
extension MainController:CustomTabBarControllerDelegate {
    func tabBarSelected(_ isRepeat: Bool) {
        print(isRepeat)
    }
}

相关文章

网友评论

      本文标题:Swift-TabBar选中item并通知controller

      本文链接:https://www.haomeiwen.com/subject/tyjmgctx.html