UITapGestureRecognizer立即调用 [英] UITapGestureRecognizer called immediately

查看:125
本文介绍了UITapGestureRecognizer立即调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试将UITapGestureRecognizer添加到imageview,如下所示

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)

这是imgPressed函数:

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) 
}

我在viewdidload中添加了3行代码,添加了一个断点并运行应用程序.我观察到的是,一旦编译器进入第一行,即让gest ...,它将立即调用action方法.甚至在应用程序开始运行之前.显然,由于window尚未加载,它会引发以下警告

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?

谢谢

推荐答案

您应使用以下语法:

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

请注意,Selector可以接受初始类型Void以及String.正确的旧式Selector初始化看起来像这样:

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()

一件事-在第一行中,您手动调用了imgPressed()函数,并返回了Void.就这样=)

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

这篇关于UITapGestureRecognizer立即调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆