ios - 基于警报选择的 Swift TabbarViewController 操作。 shouldSelect 和 didSelect 没有帮助

标签 ios swift tabbar

我想根据警报选择更改选项卡栏中的选项卡(警报 - 您确定要离开此页面吗?CASE - 是 - 根据所选选项卡更改 View 。CASE - 否 - 不要执行任何操作.留在同一页面(标签栏索引)。

我尝试使用 tabbarcontrollerdelegate 方法 didselect 和 shouldselect,但无法让它工作。


 func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

var decision : Bool?
let alert = UIAlertController(title: "You are in middle of a Quiz", message: "Do you want to end the Quiz in between !",         preferredStyle: UIAlertController.Style.alert)

alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: { _ in
            // do nothing.
            decision = false
        }))
        alert.addAction(UIAlertAction(title: "Yes",
                                      style: UIAlertAction.Style.default,
                                      handler: {(_: UIAlertAction!) in
                                        decision = true
            // go to clicked tabbar view                          
        }))
        self.present(alert, animated: true, completion: nil)

    return decision!

    }

此代码不起作用,因为在进入警报选择之前,didselect 返回 bool (在上述情况下崩溃)。解决此问题的替代方法是什么,即在单击选项卡栏时,只有在用户再次确认他想要离开当前页面(通过警报操作)后, View 才会更改。

最佳答案

shouldSelect viewController 方法中检查 viewController 是否是您的目标 View Controller 。如果不返回true,如果是则显示警报并返回false

如果选择了警报,则不执行任何操作。如果选择"is",则将目标 View Controller 指定为 selectedViewControllertabBarController

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    if viewController is DestinationViewController {            
        let alert = UIAlertController(title: "You are in middle of a Quiz", message: "Do you want to end the Quiz in between !",         preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "No", style: .default))
        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in
            tabBarController.selectedViewController = viewController
        }))
        self.present(alert, animated: true, completion: nil)
        return false
    }
    return true
}

关于ios - 基于警报选择的 Swift TabbarViewController 操作。 shouldSelect 和 didSelect 没有帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56406144/

相关文章:

iphone - Documents 目录中图像的图像缓存

ios - UISearchController:用于显示和搜索的单个与单独的表格 View

ios - UITabbarItem : - Downloaded image does not show up at Tabbar Item.

iPhone 4 - 标签栏图标

ios - Xcode 7.1 : Simulator can't be opened because the identity of developer cannot be confirmed

javascript - 使用 PhoneGap/Cordova 时如何捕获 android 和 iOS 中的 "Next"和 "Prev"按钮?

ios - GiphyCore.swift文件通过cocoapods在安装的GiphyCoreSDK中丢失

ios - TabBarController 内的 TabBarController

Swift 图表 - 突出显示中心点

ios - 不显示横幅仅在收到推送通知时振动设备