如何使用 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:)不会多次执行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)
}

你可以像这样 swift-ish:

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

我不完全确定为什么我需要将 [=16=]; 添加到该闭包的前面,但没有它它就无法工作。幸运的是,它什么也没做。