2016-10-04 46 views
3

我想知道如何在Swift 3中使用Selector,包括func要求的括號中的值。我可以在Swift中使用帶括號的選擇器嗎?

let fireRecogniser = UISwipeGestureRecognizer(target: self, action: Selector(("shootShot"))) 

^即識別器我有但該方法「shootShot」具有用於Element的參數其是enum,我有。

這裏是 'shootShot' 功能:

func shootShot(type: Element) { 

    let shot = SKSpriteNode(imageNamed: "\(type)Shot") 
    shot.texture?.filteringMode = SKTextureFilteringMode.nearest 

    shot.position = CGPoint(x: -self.frame.width/2 /*playerframe*/, y: -(self.frame.height/2) + grnd.frame.height) 
    shot.setScale(1) 

    shot.physicsBody = SKPhysicsBody(circleOfRadius: (shot.frame.height/2)) 
    shot.physicsBody?.affectedByGravity = false 
    shot.physicsBody?.allowsRotation = true 
    shot.physicsBody?.isDynamic = true 
    shot.physicsBody?.restitution = 0 
    shot.physicsBody?.angularDamping = 0 
    shot.physicsBody?.linearDamping = 0 
    shot.physicsBody?.friction = 0 
    shot.physicsBody?.categoryBitMask = Contact.Shot.rawValue 
    shot.physicsBody?.contactTestBitMask = Contact.Enemy.rawValue 

    self.addChild(shot) 

    // THIS WILL DEPEND ON DIFFICULTY 
    let spin = SKAction.rotate(byAngle: 1, duration: 0.3) 
    shot.run(SKAction.repeatForever(spin)) 
    let move = SKAction.moveTo(x: self.frame.width/2, duration: 3.0) 
    let remove = SKAction.removeFromParent() 
    shot.run(SKAction.sequence([move, remove])) 
} 

正如你所看到的,該方法具有Element的功能需要。

有關如何將該參數包含在我的Selector中的幫助? 謝謝。 :)

回答

2

輸入您選擇這樣的斯威夫特3

let fireRecogniser = UISwipeGestureRecognizer(target: self, action: #selector(shootShot(element:))) 
+0

更新和固定:) – pedrouan

1

這是可能的...如果你正在執行的選擇之一。

有具有with:參數的perform()過載。您在with:參數中傳遞的參數將傳遞給選擇器方法。

實施例:

// in some NSObject subclass's method 
perform(#selector(myMethod), with: "Hello") 

// in the same class 
func myMethod(x: String) { 
    print(x) 
} 

如果執行第一行, 「你好」 將被打印。

然而,侑情況下,因爲你不是選擇的演員,你不能用你想要的參數進行選擇。你傳遞目標和行動手勢之前

var shotElement: Element! 

您可以將其設置爲某個值:

您可以通過添加一個類級別的變量,表示要調用該方法,其Element解決此識別器。

然後訪問它在shootShot

let shot = SKSpriteNode(imageNamed: "\(shotElement)Shot") 

我承認這不是完美的解決辦法,但它是最簡單的。

相關問題