Granit Granit - 8 days ago 6
Swift Question

Create UIButtons dynamically with for loop in Swift

I am trying to add buttons dynamically to a scroll view after pressing another button.

I created a custom UIView which I want to add to the scroll view.

Below you can find the code how I am trying to do it:

var buttonY: CGFloat = 0 // our Starting Offset, could be 0
for _ in audioCommentsArray {
UIView.animateWithDuration(0.15, animations: {

let commentView = AudioCommentView(frame: CGRectZero)
commentView.frame = CGRect(x: 0, y: buttonY, width: 75, height: 75)

buttonY = buttonY + 75 // we are going to space these UIButtons 75px apart

commentView.alpha = 1.0

audioCommentsListScrollView.addSubview(commentView)
})
}


I want to add these commentView's using a simple animation. However only the last commentView is added correctly to the scrollView whereas the above views are added like this:

enter image description here

Only the background of the commentView is shown whereas the other elements are not visible.

Does anyone have an idea what I might be missing? Adding views using a for loop shouldn't be complicated as I have done this many times before but this time I seem to miss something?

Thank you in advance!

Answer

The UIView animations are overlapping and interfering with each other as you process them through the loop. Instead, you should chain them so that the next animation does not interfere with the other. Delete the loop. Then call the animations one after the other in the completion handler. You can call it recursively to ensure each button is animated.

    var count = 0

    func startButtonsAnimation() {

    UIView.animateWithDuration(0.15, animations: {

                let commentView = AudioCommentView(frame: CGRectZero)
                commentView.frame = CGRect(x: 0, y: buttonY, width: 75, height: 75)

                buttonY = buttonY + 75  // we are going to space these UIButtons 75px apart

                commentView.alpha = 1.0

                audioCommentsListScrollView.addSubview(commentView)
            }, completion: { (value: Bool) in 
                      if self.count < self.audioCommentsArray.count { 
                           self.count += 1
                           self.startButtonsAnimation()
                      }
    })