2015-03-02 41 views
1

中製作多個對象所以我試圖通過使用for in循環創建10個按鈕,並使用CADisplayLink使所有這10個按鈕向下移動。問題是我的CADisplayLink只移動了其中一個按鈕,我希望它移動所有的10個按鈕。請幫忙!提前致謝!如何使用for-in-loop在CADisplayLink

var button: UIButton! 



override func viewDidLoad() { 
    super.viewDidLoad() 

    var displayLink = CADisplayLink(target: self, selector: "handleDisplayLink:") 
    displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) 

    for index in 0...10 { 

     var xLocation:CGFloat = CGFloat(arc4random_uniform(300) + 30) 

     button = UIButton.buttonWithType(UIButtonType.System) as UIButton 

     button.frame = CGRectMake(xLocation, 10, 100, 100) 
     button.setTitle("Test Button", forState: UIControlState.Normal) 
     button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside) 

     self.view.addSubview(button) 

     } 



} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 

} 

func handleDisplayLink(displayLink: CADisplayLink) { 

    for index in 0...10 { 

     var buttonFrame = button.frame 
     buttonFrame.origin.y += 1 
     button.frame = buttonFrame 
     if button.frame.origin.y >= 500 { 
      displayLink.invalidate() 
     } 
    } 
} 


func buttonAction(sender: UIButton) { 
    sender.alpha = 0 
} 

}

回答

0

你只得到了一個引用您在viewDidLoad創建的10個按鈕中的一個。使用數組類型按鈕[UIButton]來存儲全部10個,然後在您的CADisplayLink回調期間循環遍歷每個10。

你的宣言是:

var buttons: [UIButton] = Array(count: 10, repeatedValue: UIButton.buttonWithType(.System) as! UIButton) 

而且您在最初的代碼中引用一個按鈕任何時候使用數組索引運算符您for循環的當前索引引用按鈕:

buttons[index] 

Swift陣列和標準庫參考的概述在這裏:

因此所提供的代碼是:

var buttons: [UIButton] = Array(count: 10, repeatedValue: UIButton.buttonWithType(.System) as! UIButton) 

override func viewDidLoad() { 
    super.viewDidLoad() 

    var displayLink = CADisplayLink(target: self, selector: "handleDisplayLink:") 
    displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) 

    for index in 0...10 { 

     var xLocation:CGFloat = CGFloat(arc4random_uniform(300) + 30) 

     buttons[index].frame = CGRectMake(xLocation, 10, 100, 100) 
     buttons[index].setTitle("Test Button \(index)", forState: UIControlState.Normal) 
     buttons[index].addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside) 

     self.view.addSubview(buttons[index]) 

     } 



} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 

} 

func handleDisplayLink(displayLink: CADisplayLink) { 

    for index in 0...10 { 

     var buttonFrame = buttons[index].frame 
     buttonFrame.origin.y += 1 
     buttons[index].frame = buttonFrame 
     if buttons[index].frame.origin.y >= 500 { 
      displayLink.invalidate() 
     } 
    } 
} 


func buttonAction(sender: UIButton) { 
    sender.alpha = 0 
} 
+0

我將如何寫? – 2015-03-02 17:59:28

+0

你有工作嗎?如果是這樣,請將答案標記爲正確,否則,我很樂意提供進一步的幫助。 – Ralfonso 2015-03-02 18:10:11

+0

我似乎無法得到它,你能告訴我整個事情會在一起嗎? – 2015-03-02 20:28:34

相關問題