简体   繁体   中英

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.

UIAlertController doesn't have a property tag . The hint is in the error "'UIAlertController' does not have a member named 'tag'".

UIAlertController is not a subclass of UIView it is a subclass of UIViewController .

There are almost no reasons for ever using tag though, even when it is available.

What you probably want is to set it into a property instead.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM