簡體   English   中英

Swift:在touchesBegan中使用switch語句

[英]Swift: Using switch statement in touchesBegan

我想在SKScene清理我的touchesBegan(..) 我想創建一個case語句而不是我的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
    }
}

如果你想要===行為如下所示,你可以編寫一種奇怪但功能正常的switch

switch(true){
        case self.nodeAtPoint(location) === playLabel : buildLevelSelect()
        case self.nodeAtPoint(location) === aboutLabel : createAboutView()
        case self.nodeAtPoint(location) === storeLabel : createStore()
        default : break
}

在我看來,這仍然比if-else鏈更清晰。

完成此操作的最簡單方法是填充節點的.name屬性,然后您可以改為使用該名稱。 那么你的開關看起來像這樣:

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

您還可以在switch語句中轉換對象,然后您的代碼按預期工作

    if let touch = touches.first as UITouch! {

        let touchLocation = touch.location(in: self)

        switch self.atPoint(touchLocation) {
            case redBox as SKSpriteNode:
                print("touched redBox")
            case greenBox as SKSpriteNode:
                print("touched greenBox")
            default:
                print("touched nothing")
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM