swift 点击tabbar'购物车'需要登录,登录dismi

2020-04-21  本文已影响0人  喵喵粉

UITabBarController有[首页, 分类, 购物车, 我的]页面

跳转需求:
点击购物车需要判断是否已登录,未登录就present 登录页面,登录后跳到购物车页面

方法:
自定义UITabBarControllerBaseTabBarVC

  1. 在代理tabBarController:shouldSelect:拦截事件
    判断:点击购物车+ 是否登录,满足条件就present 登录页面

  2. 重写viewDidAppear
    present登录页面dismiss时,在viewDidAppear判断是否已登录

class BaseTabBarVC: UITabBarController {

    ///点击tabbar'购物车'需要登录,登录dismiss后 跳转到'购物车'
    fileprivate var loginBackSelectedTuple: (index: Int, shouldCompare: Bool) = (0, false)
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        ///默认选中第n个tab
        selectedIndex = 0
        
        delegate = self
    }
    
    ///当present的loginVC dismiss时tabbar调用viewDidAppear
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if loginBackSelectedTuple.shouldCompare, extIsLogin() {
            selectedIndex = loginBackSelectedTuple.index
            loginBackSelectedTuple.shouldCompare = false
        }
    }
}
extension BaseTabBarVC: UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        guard let vc = (viewController as? BaseNavVC)?.topViewController else { return false }
        
        ///未登录 + 购物车
        if vc.clsName == "CartVC", !extIsLogin() {

            ///登录
            extPresentLoginVC()
            
            ///记录登录后需要选中的selectedIndex
            guard let vcs = viewControllers else { return false }
            let selectedIndex = (vcs as NSArray).index(of: viewController)
            
            loginBackSelectedTuple = (selectedIndex, true)
            
            return false
        }
        
        return true
    }
}
上一篇下一篇

猜你喜欢

热点阅读