我想根据警报选择更改选项卡栏中的选项卡(警报 - 您确定要离开此页面吗?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 指定为 selectedViewController
在tabBarController
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/