使UITabBar在切换选项卡之前等待用户输入

时间:2018-09-11 14:18:26

标签: ios swift uitabbarcontroller uialertcontroller

我有一个带有5个标签的UITabBar。选择中间选项卡后,我希望弹出UIAlertController操作表,等待用户操作,然后在用户从工作表中选择后加载新视图,因为我需要工作表中的数据才能正确加载视图。

我目前有以下代码:

extension CustomTabBarController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        guard let index = viewControllers?.index(of: viewController) else {
            return false
        }
        if index == 2 {
            var choice = CreateChoice()

            let alert = UIAlertController(title: "Select Creation Type", message: "Please select the desired creation type", preferredStyle: .actionSheet)

            let action1 = UIAlertAction(title: "Quick Create", style: .default) { (action:UIAlertAction) in
                choice.choice = "quick"
            }

            let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) in
                choice.choice = "cancel"
            }

            let action3 = UIAlertAction(title: "Full Create", style: .default) { (action:UIAlertAction) in
                choice.choice = "full"
            }

            alert.addAction(action1)
            alert.addAction(action2)
            alert.addAction(action3)

            present(alert, animated: true, completion: nil)
            print(choice.choice)
            if choice.choice == "cancel" {
                return false
            }
            return true
        }
        return true
    }
} 

除了在用户从操作表中选择任何内容之前加载新视图之外,这在所有方面都起作用。是否可以让UITabBar等待操作,还是我需要以其他方式进行处理?

1 个答案:

答案 0 :(得分:1)

逻辑是始终在委托中返回false以编程方式更改为所需的索引,以防用户在警报中点击所需的操作。

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    guard let index = viewControllers?.index(of: viewController) else {
        return false
    }
    if index == 2 {

        let alert = UIAlertController(title: "Select Creation Type", message: "Please select the desired creation type", preferredStyle: .actionSheet)

        let action1 = UIAlertAction(title: "Quick Create", style: .default) { (action:UIAlertAction) in
            tabBarController.selectedIndex = 2
        }

        let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) in
            // Do nothing
        }

        let action3 = UIAlertAction(title: "Full Create", style: .default) { (action:UIAlertAction) in
            tabBarController.selectedIndex = 2
        }

        alert.addAction(action1)
        alert.addAction(action2)
        alert.addAction(action3)

        present(alert, animated: true, completion: nil)
        return false
    }
    return true
}

如果可以的话,您可以避免选择变量。