koushik v koushik v - 2 years ago 112
Swift Question

UITapGestureRecognizer called immediately

I am trying to add a tapgesturerecognizer to a imageview as shown below

let gest=UITapGestureRecognizer(target: self, action: Selector(imgPressed()));

And here is the
function :

func imgPressed()
let alert=UIAlertController(title: "Img", message: "img pressed", preferredStyle: .Alert)
let okButton=UIAlertAction(title: "Ok", style: .Default, handler: nil)
presentViewController(alert, animated: true, completion: nil)

I added the 3 lines of code in viewdidload, added a breakpoint and ran the application.What i observed is that once the compiler comes to the first line i.e let gest..., it is calling the action method immediately even before the application starts running.Since obviously the window is yet to load, it throws the below warning

Warning: Attempt to present on whose view is not in the window hierarchy!

I don't understand why this is happening .Can someone please help me with this issue?

Thank you

Answer Source

You should use following syntax:

let gest = UITapGestureRecognizer(target: self, action: #selector(imgPressed))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download