koushik v koushik v - 5 months ago 26
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()));
gest.delegate=self
thalaImg.addGestureRecognizer(gest)


And here is the
imgPressed
function :

func imgPressed()
{
let alert=UIAlertController(title: "Img", message: "img pressed", preferredStyle: .Alert)
let okButton=UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(okButton)
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

You should use following syntax:

let gest = UITapGestureRecognizer(target: self, action: #selector(imgPressed))