I have a UIAlertController with multiple UIAlertActions. I am wanting to access the UIAlertAction title property of the selected action.
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))
Accessing the ac.title property only access the AlertController title property.
Looking into the Apple documentation, it looks like I may need to use something like
var title: String? { get }
However I'm not familiar on how to use this syntax.
The syntax in the documentation shows you how the title
property is declared, not how you would refer to it in your code (though it can give some insights).
Since it is a property, you can access it via the dot notation .title
if you have an instance of UIAlertAction
. Luckily, you do have access to the selected instance of UIAlertAction
: the parameter passed to the handler
function!
In the handler of the alert action, i.e. setFilter
, you can access its parameter's .title
. This will be the selected action's title.
func setFilter(_ action: UIAlertAction) {
let selectedActionTitle = action.title
...
}