2014-07-19 131 views
0

我無法弄清楚如何在swift中使用我的switch語句,以便當我單擊任一按鈕時它將執行println()。每次我點擊任一按鈕它只是執行默認。使用按鈕快速切換語句

class ViewController: UIViewController{ 

    var addOne : UIButton = UIButton(frame: CGRectMake(0, 0, 40, 40)) 
    var addFive : UIButton = UIButton(frame: CGRectMake(0, 0, 40, 40)) 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     addOne.setTitle("+1", forState: UIControlState.Normal) 
     addOne.backgroundColor = UIColor.blackColor() 
     addOne.center = (CGPointMake(40, 250)) 
     addOne.addTarget(self, action: "player", forControlEvents: UIControlEvents.TouchUpInside) 
     view.addSubview(addOne) 

     addFive.setTitle("+5", forState: UIControlState.Normal) 
     addFive.backgroundColor = UIColor.blackColor() 
     addFive.center = (CGPointMake(200, 250)) 
     addFive.addTarget(self, action: "player", forControlEvents: UIControlEvents.TouchUpInside) 
     view.addSubview(addFive) 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func player(){ 

     switch (true){ 

     case addOne: 
      println("goodbye") 
     case addFive: 
      println("hello world") 

     default: 
      println("hello") 
     } 

    } 

} 

回答

1

更改此:

addOne.addTarget(self, action: "player", forControlEvents: UIControlEvents.TouchUpInside) 

這樣:

addOne.addTarget(self, action: "player:", forControlEvents: UIControlEvents.TouchUpInside) 

這:

addFive.addTarget(self, action: "player", forControlEvents: UIControlEvents.TouchUpInside) 

這樣:

addFive.addTarget(self, action: "player:", forControlEvents: UIControlEvents.TouchUpInside) 

注意在除了結腸 「的球員:」

接下來,更改此:

func player(){ 

    switch (true){ 

    case addOne: 
     println("goodbye") 
    case addFive: 
     println("hello world") 

    default: 
     println("hello") 
    } 

} 

這樣:

func player(sender: UIButton){ 

    switch (sender){ 

    case addOne: 
     println("goodbye") 
    case addFive: 
     println("hello world") 

    default: 
     println("hello") 
    } 

} 
+0

爲什麼添加分號會影響我的switch語句工作? – user3856516

+1

分號表示選擇器接受一個參數。在按鈕的情況下,這意味着它將發送自己作爲參數。以前,你的開關參數是'true'。因爲您試圖將按鈕與「true」進行比較,所以您的所有案例都未評估爲「true」。通過將按鈕作爲參數傳遞,我們可以正確地將您的按鈕屬性與觸發該操作的按鈕進行比較。 – Logan