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



我有一个带有多个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标题属性。

查看苹果的文档,我可能需要使用之类的东西

var title: String? { get }

然而,我不熟悉如何使用这种语法。

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

由于它是一个属性,如果您有UIAlertAction的实例,则可以通过点表示法.title访问它。幸运的是,您确实可以访问UIAlertAction的选定实例:传递给handler函数的参数!

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

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

接受的答案对我来说有点不清楚,即使是Swift相当流利的人。下面是一个简单的例子,说明如何通过返回操作标题值的操作轻松构建UIAlertController:

let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "title", style: .default, handler: { [self] action in
let actionTitle = action.title
}))

最新更新