Riyazul Aboobucker Riyazul Aboobucker - 11 months ago 89
iOS Question

Setting a tag for UIAlertController in SWIFT?

How to set tag for the alert view in swift. I couldn't set the tag

alert.tag = 1
, if I did, I get an error like
'UIAlertController' does not have a member named 'tag'
. Below is the code that i have written,

var alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "YES", style: UIAlertActionStyle.Default, handler:{ (ACTION :UIAlertAction!)in }))
alert.addAction(UIAlertAction(title: "NO", style: UIAlertActionStyle.Default, handler:{ (ACTION :UIAlertAction!)in }))

alert.tag = 1 // Error is shown here

self.presentViewController(alert, animated: true, completion: nil)

We used to set tags for alert views in Obj-C. Could someone please help me on this. Thanks in advance.

Answer Source

I like the answer from @Fogmeister and wanted to add:

The only reason you want to use a tag on an alert view is to identify it so that you can differentiate which one is calling the delegate method (without the overhead of storing each potential in a property and checking all the pointers). This isn't ideal, but it's a quick work around, and as stated previously it's usually a hack of some kind.

The whole delegation approach is replaced in UIAlertController with a block based interface so there should no longer be any need to use the tag. The blocks you supply to the alert actions can reference self with dedicated code and can capture any local variables you need to so there should be no need to do the same thing that you might have been using a tag for previously.