Swift:在touchesBegan中使用switch语句(Swift: Using switch statement in touchesBegan)

编程入门 行业动态 更新时间:2024-10-06 01:43:45
Swift:在touchesBegan中使用switch语句(Swift: Using switch statement in touchesBegan)

我想清理SKScene touchesBegan(..) 。 我想提出一个案例陈述,而不是我的if .. else链。 但是,我在实施时遇到了错误,这表明我不知道如何在引擎盖下进行平等。

在代码之前:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch: AnyObject in touches { let location = touch.locationInNode(self) if self.nodeAtPoint(location) === playLabel { buildLevelSelect() } else if self.nodeAtPoint(location) === aboutLabel { createAboutView() } else if self.nodeAtPoint(location) === storeLabel { createStore() } } }

代码后:点击后,一些标签点击工作,但其他人提出了一个Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode 0x0)错误:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch: AnyObject in touches { let location = touch.locationInNode(self) switch(self.nodeAtPoint(location)){ case playLabel : buildLevelSelect() case aboutLabel : createAboutView() case storeLabel : createStore() default : break } }

I want to clean up my touchesBegan(..) in SKScene. I wanted to make a case statement instead of my if .. else chain. However, I get errors when implementing, which suggests that I don't know how equality is done under the hood.

Before code:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch: AnyObject in touches { let location = touch.locationInNode(self) if self.nodeAtPoint(location) === playLabel { buildLevelSelect() } else if self.nodeAtPoint(location) === aboutLabel { createAboutView() } else if self.nodeAtPoint(location) === storeLabel { createStore() } } }

After code: After clicking around, some label clicks work, but some others raise a Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode 0x0) error:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch: AnyObject in touches { let location = touch.locationInNode(self) switch(self.nodeAtPoint(location)){ case playLabel : buildLevelSelect() case aboutLabel : createAboutView() case storeLabel : createStore() default : break } }

最满意答案

最简单的方法是通过填充节点的.name属性,然后您可以切换名称。 那么你的开关看起来像这样:

switch (self.nodeAtPoint(location).name ?? "") { case "playLabel" : buildLevelSelect() case "aboutLabel" : ...

The easiest way to accomplish this would be by populating the .name property of your nodes, so then you could switch on the name instead. So then your switch would look like this:

switch (self.nodeAtPoint(location).name ?? "") { case "playLabel" : buildLevelSelect() case "aboutLabel" : ...

更多推荐

本文发布于:2023-08-07 11:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464073.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   touchesBegan   Swift   statement   switch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!