簡體   English   中英

如何使用for-in-loop生成按鈕數組,然后使用CADisplayLink為它們設置動畫

[英]How to generate an array of buttons using a for-in-loop and then animate them with a CADisplayLink

我試圖使用for-in-loop生成由10個按鈕組成的數組,然后使用CADisplayLink內的for-in-loop對它們進行動畫處理,但問題是僅創建了一個按鈕並對其進行了動畫處理。 請幫忙! 提前致謝!

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 - 1{

        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 - 1{

        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
}

}

構造函數Array(count:, repeatedValue:)不會Array(count:, repeatedValue:)執行UIButton構造函數。 它接收一個值,然后重復該值,您碰巧在行中實例化了指針。

您所做的工作與以下功能相同:

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

以這種方式拆分參數使Array構造函數的操作更加清晰。


您可能想做的更像是:

var buttons:[UIButton] = Array()
for index in 1...10 {
  buttons.append(UIButton.buttonWithType(.System) as UIButton)
}

您可能會變得更加敏捷:

var buttons:[UIButton] = Array(Range(1...10)).map( { $0; return UIButton.buttonWithType(UIButtonType.System) as UIButton } )

我不完全確定為什么需要增加$0; 到該關閉的最前面,但沒有它,它拒絕工作。 幸運的是,它什么也沒做。

暫無
暫無

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

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