UITapGestureRecognizer called immediately

前提是你 提交于 2019-12-31 01:45:11

问题


I am trying to add a UITapGestureRecognizer 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


回答1:


You should use following syntax:

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

Note, that Selector can accept initial type Void as well as String. Properly old-style Selector initialization looks like this:

let action: Selector = Selector("imgPressed")

Now you may check, that if you will try combine new style with old style you will get compilation error:

let action = Selector(imgPressed) // Error!

Funny thing is that you probably will try to resolve this error by appending bracers, and you will not have any errors after that! But this is completely useless. Look at following 3 lines of code, they are equivalent

let action = Selector(imgPressed())
let action = Selector(Void())
let action = Selector()

exept one thing - in first line you called imgPressed() function, returned Void, by your hands. Thats it =)




回答2:


Change your gesture line like following if swift 2.0 or less

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

if you are using swift 2.2 or greater than that

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

Hope this will help you.



来源:https://stackoverflow.com/questions/37943477/uitapgesturerecognizer-called-immediately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!