如何访问 Swift 中的 UIAlertAction 标题 属性?

How to access UIAlertAction title property in Swift?

我有一个带有多个 UIAlertActions 的 UIAlertController。我想访问所选操作的 UIAlertAction 标题 属性。

    let ac = UIAlertController(title: "Choose Filter", message: nil, preferredStyle: .actionSheet)
    ac.addAction(UIAlertAction(title: "CIBumpDistortion", style: .default, handler: setFilter))
    ac.addAction(UIAlertAction(title: "CIGaussianBlur", style: .default, handler: setFilter))
    ac.addAction(UIAlertAction(title: "CIPixellate", style: .default, handler: setFilter))
    ac.addAction(UIAlertAction(title: "CISepiaTone", style: .default, handler: setFilter))
    ac.addAction(UIAlertAction(title: "CITwirlDistortion", style: .default, handler: setFilter))
    ac.addAction(UIAlertAction(title: "CIUnsharpMask", style: .default, handler: setFilter))
    ac.addAction(UIAlertAction(title: "CIVignette", style: .default, handler: setFilter))
    ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        

访问 ac.title 属性 仅访问 AlertController 标题 属性。

查看 Apple 文档,看来我可能需要使用类似

的东西
var title: String? { get }

但是我不熟悉如何使用这种语法。

文档中的语法向您展示了 title 属性 是如何 声明的 ,而不是您在代码中如何引用它(尽管它可以提供一些见解)。

因为它是 属性,如果您有 UIAlertAction 的实例,则可以通过点符号 .title 访问它。幸运的是,您确实可以访问 UIAlertAction 的选定实例:传递给 handler 函数的参数!

在警报操作的处理程序中,即 setFilter,您可以访问其参数的 .title。这将是所选操作的标题。

func setFilter(_ action: UIAlertAction) {
    let selectedActionTitle = action.title
    ...
}