You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中LGSideMenuController侧边栏didSelect方法失效求助

解决LGSideMenuController侧边栏点击无法跳转页面的问题

我明白你的困扰——侧边栏能正常弹出,点击列表项也能打印日志,但就是跳不到目标页面对吧?问题的核心很明确:你的SideMenuViewController没有被嵌入到UINavigationController中,导致调用self.navigationController?.pushViewController(...)时,navigationController是nil,跳转代码根本没执行。

下面是具体的修复步骤:

1. 修改AppDelegate中的侧边栏配置

在rootViewController()函数里,把侧边栏控制器包裹进一个UINavigationController,再传给LGSideMenuController:

func rootViewController() { 
    let appDelegate = UIApplication.shared.delegate as? AppDelegate 
    let mainViewController = DashboardViewController.instantiate(fromAppStoryboard: .Main) 
    let leftViewController = SideMenuViewController.instantiate(fromAppStoryboard: .Main) 
    
    // 关键:给侧边栏控制器添加导航容器
    let leftNavigationController = UINavigationController(rootViewController: leftViewController)
    
    let sideMenuController = LGSideMenuController(
        rootViewController: UINavigationController(rootViewController: mainViewController),
        leftViewController: leftNavigationController, // 传入带导航的侧边栏
        rightViewController: nil
    ) 
    
    sideMenuController.delegate = self 
    sideMenuController.leftViewWidth = UIScreen.main.bounds.width - 150 
    sideMenuController.leftViewPresentationStyle = .slideAbove 
    
    // 删掉这行多余的push操作,已经设置rootViewController了
    // self.navigationController?.pushViewController(sideMenuController, animated: true) 
    
    appDelegate?.window?.rootViewController = sideMenuController 
    appDelegate?.window?.makeKeyAndVisible() 
}

2. 优化侧边栏点击后的体验(可选)

在SideMenuViewController的didSelectRowAt方法里,添加收起侧边栏的代码,让跳转体验更流畅:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    print("did select is working fine") 
    let storyBoard = UIStoryboard(name: "Main", bundle: nil) 
    let vc = storyBoard.instantiateViewController(withIdentifier: "CustomerListViewController") as! CustomerListViewController 
    
    // 先收起侧边栏
    self.sideMenuController?.hideLeftView(animated: true)
    // 现在navigationController不为nil,跳转正常执行
    self.navigationController?.pushViewController(vc, animated: true) 
}

3. 最后检查一个细节

确认你的CustomerListViewController在Storyboard中的Storyboard ID确实设置为了CustomerListViewController,避免因为ID不匹配导致实例化失败。

这样修改后,侧边栏点击列表项就能正常跳转到目标页面了!

内容的提问来源于stack exchange,提问作者Rohit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:02:48