UITapGestureRecognizer称为立即
我尝试添加UITapGestureRecognizer
到imageview
如下图所示UITapGestureRecognizer称为立即
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)
}
我加了3行代码中viewdidload
,添加了一个断点并运行了应用程序。我观察到的是,一旦编译器进入第一行,即let gest ...,即使在应用程序开始运行之前,它也会立即调用操作方法。显然window
尚未加载,它抛出下面的警告
Warning: Attempt to present on whose view is not in the window hierarchy!
我不明白为什么会这样。可有人请帮助我这个问题?
谢谢
应使用以下语法:
let gest = UITapGestureRecognizer(target: self, action: #selector(imgPressed))
注意,那Selector
可以接受初始型Void
以及String
。正确旧式Selector
初始化看起来是这样的:
let action: Selector = Selector("imgPressed")
现在你可以检查,如果你会尝试结合与老款新样式,你会得到编译错误:
let action = Selector(imgPressed) // Error!
有趣的是,你可能会尝试通过追加护腕来解决这个错误,之后你不会有任何错误!但这完全没用。看看下面3行代码,两者是等价
let action = Selector(imgPressed())
let action = Selector(Void())
let action = Selector()
exept一两件事 - 在第一行,你叫imgPressed()
函数,返回Void
,通过你的手。这就是它=)
改变你的姿态线一样,如果以下SWIFT 2.0或更低
let gest=UITapGestureRecognizer(target: self, action: Selector("imgPressed"));
如果您正在使用SWIFT 2.2或高于
let gest=UITapGestureRecognizer(target: self, action: #selector(imgPressed));
希望这将更大帮你。
好吧,我将**选择器(imgPressed())**更改为**#选择器(imgPressed)**。立即调用方法的问题已解决,但现在当我点击图像时,方法没有被调用 –
@koushikv确保'UIImageView'中的'userInteractionEnabled'属性设置为'true'。在'viewDidLoad'中添加'thalaImg.userInteractionEnabled = true' –
您需要将userInterActionEnabled设置为true –
“FUNC imgPressed() { 设警报= UIAlertController(标题: “图”,消息: “IMG按下”,preferredStyle:.Alert) 让okButton = UIAlertAction(标题: “OK”,样式:。默认情况下,处理程序:无) alert.addAction(okButton) presentViewController(警报,动画:真,完成:无) }” –
好吧删除()imgPressed method.And后双引号 “imgPressed”。 – Pushpa
你正在使用哪个swift版本意味着swift 2.0或swift 3.0吗? –