首页 > 解决方案 > 警报弹出当前无法正常工作

问题描述

我正在构建一个图表,其中包含带有 onTap 的条形,它调用一个函数来显示总数。该函数具有以下代码,但不喜欢出现警报,“使用未解析的标识符”出现“错误。

在我的代码顶部,我导入了 UIKit,我的功能如下:

func displayTotals(monthSelected: Int, monthTotalQty: Int, monthTotalCurrency: Int){
    let alert = UIAlertController(title: "\(monthSelected) Totals", message: "Quantity \(monthTotal) | Total \(monthTotalCurrency)", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .destructive) { _ in
        return
    })
    present(alert, animated: true)
}

标签: xcode

解决方案


似乎您在 UIViewController 之外调用此方法。在这种情况下,您可以将视图控制器添加为 func 的参数。

func displayTotals(rootVC: UIViewController,  monthTotal: Int,  monthSelected: Int, monthTotalQty: Int, monthTotalCurrency: Int){
        let alert = UIAlertController(title: "\(monthSelected) Totals", message: "Quantity \(monthTotal) | Total \(monthTotalCurrency)", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .destructive) { _ in
            return
        })
        rootVC.present(alert, animated: true)
    }

或者,您可以静态获取根 ViewController,而无需更改 func 的 le 符号:

   func displayTotals( monthTotal: Int,  monthSelected: Int, monthTotalQty: Int, monthTotalCurrency: Int){
            let alert = UIAlertController(title: "\(monthSelected) Totals", message: "Quantity \(monthTotal) | Total \(monthTotalCurrency)", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok", style: .destructive) { _ in
                return
            })
  var rootVC = UIApplication.shared.keyWindow?.rootViewController
  rootVC?.present(alert, animated: true)
        }

推荐阅读