【问题标题】:Create tab bar item that triggers Alert view controller创建触发警报视图控制器的选项卡栏项
【发布时间】:2019-10-15 22:05:22
【问题描述】:

我有一个UITabBarController,我想创建一个只会触发警报视图控制器的项目。

我希望警报显示在按下按钮的视图控制器的顶部。

这是我现在的代码,但由于某种原因它不起作用:

override func viewDidLoad() {
    super.viewDidLoad()
 self.tabBarController?.delegate = self
}

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

    if item.title == "Title"{
        let action = UIAlertAction(title: "OK", style: .default, handler: { (nil) in

            self.tabBarController?.selectedIndex = 0
        })
        let alert = UIAlertController(title: "Feature not active yet", message: "Will be added soon", preferredStyle: .alert)
        alert.addAction(action)
        present(alert, animated: true, completion: nil)

    }
}

它向我显示警报,但不会移动到 OK 操作处理程序中的索引 0。

【问题讨论】:

标签: ios swift uitabbarcontroller


【解决方案1】:

https://github.com/pkesaj/TabbarItemAlert

这是它如何工作的示例。

编辑:

您需要添加一个 UITabbarControllerDelegate 并在 viewWillAppear 添加:

self.tabbarController?.delegate = self

然后在类的主体中:

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {

    if tabBarController.selectedIndex == 2{
        tabBarController.selectedIndex = 0
        let alert = UIAlertController(title: "Do something", message: "With this", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "A thing", style: .default) { action in
        })
        self.present(alert, animated: true, completion: {
        })
    }
}

【讨论】:

  • 我添加了我的代码,我尝试将其更改为您的 didSelect 但它不起作用,有什么想法吗?
  • 你是否在“:”之后添加了 UITabbarControllerDelegate 并且你是否将 delegate = self 放入 viewWillAppear 中?
  • @H.Epstein 在 .delegate = self 处设置断点并在控制台输入“po self.tabbarcontroller”,它必须是 != nil。如果不是 nil,那么你必须检查 delegate 是否只分配在一个地方。
  • @pkesaj 这将始终打开警报作为“tabBarController.selectedIndex = 0”的背景视图,如何更改此行使其成为先前选择的索引
【解决方案2】:

@Non-escaping 和@Escaping 在swift 4 中的区别

@非转义

1.Non-escaping 是默认的。

2.将闭包作为函数传递。

3.Function Before Returns @non-escaping Closure 被调用。

4.不再存在于记忆中。

5.Compiler 知道@non-escaping Closure Handle 内存分配。它会 注意记忆。

6. 调用函数时必须且应该提供 [Weak self]。它是安全的。因为 @non-escaping 闭包在函数返回之前被调用。

@转义

1 转义不是默认值。 Swift 1X ,2X @escaping 是默认的。

2.将闭包作为函数传递。

3.@escaping闭包被调用后函数返回。

4.@escaping Closure Memory 在执行时存在。

5.函数外@escaping闭包也执行。

6. 大多数开发者认为@escaping 中的第-3 点如何在函数返回后调用@escaping 闭包。实际上称为自上而下的代码认为这是 从上到下意味着像 .Sync。但在我们的案例中,.Async 有效。

如果您不了解 .Sync.Async

.Sync 表示一个接一个地执行。

.异步。随机执行。所以函数在 @escaping 闭包后返回
执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多