如何以编程方式创建动作的选项卡项

时间:2019-07-18 16:09:02

标签: swift

我已经创建了一个带有代码的标签栏,但是我不知道当某人单击某个项目时如何捕获,我不知道该怎么做?

private func setNav()
{
    tabBar = UITabBarController()
    menuItemNavList = Array<UINavigationController>()
    for i in (0..<menuItemModelList.count) {
        menuItemNavList.append(createNavController(title: menuItemModelList[i].title ?? "", imageName: menuItemModelList[i].iconUrl ?? "p"))
    }
    tabBar.viewControllers = menuItemNavList
    tabBar.tabBar.tintColor = .white
    tabBar.tabBar.barTintColor = UIColor(red: 31/255, green: 192/255, blue: 241/255, alpha: 1.0)
    self.view.addSubview(tabBar.view)
}

private func createNavController(title: String, imageName: String)-> UINavigationController
{
    let viewController = UIViewController()
    let navController = UINavigationController(rootViewController: viewController)
    navController.tabBarItem.title = title
    let url = URL(string: imageName)
    let data = try? Data(contentsOf: url!)
    navController.tabBarItem.image = data != nil ? UIImage(data: data!) : UIImage(named: "icono_home")
    return navController
}

1 个答案:

答案 0 :(得分:1)

如果我没弄错您的要求,则此委托函数可以:

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    //If you wanna do something to an item with its index
    let indexOfTab = tabBar.items?.index(of: item)
    if indexOfTab == 0 {
        // The user has tapped the first item
    }
    //Else you directly get the tapped item here
    print(item)
}

确保您的控制器是选项卡栏的代理(此代理功能才能正常工作)