ios - 在 Swift 中使用 for 循环动态创建 UIButton

标签 ios swift for-loop

我正在尝试在按下另一个按钮后将按钮动态添加到 ScrollView 。

我创建了一个自定义 UIView,我想将其添加到 ScrollView 。

您可以在下面找到我尝试执行此操作的代码:

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)
                })
            }

我想使用简单的动画添加这些 commentView。但是,只有最后一个 commentView 被正确添加到 scrollView 而上面的 View 是这样添加的:

enter image description here

仅显示 commentView 的背景,而其他元素不可见。

有谁知道我可能遗漏了什么?使用 for 循环添加 View 应该不会很复杂,因为我以前做过很多次,但这次我似乎错过了什么?

提前致谢!

最佳答案

当您通过循环处理它们时,UIView 动画相互重叠和干扰。相反,您应该将它们链接在一起,以便下一个动画不会干扰另一个。删除循环。然后在完成处理程序中一个接一个地调用动画。您可以递归调用它以确保每个按钮都具有动画效果。

    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()
                      }
    })

关于ios - 在 Swift 中使用 for 循环动态创建 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40852562/

相关文章:

ios - 如何使用 swift 将 UI 对象连接到 Xcode 6 中的 cocoa 类的导出

javascript - 如何将一个很长的 for 循环分解成更小、更易读但仍能执行的部分?

Java 为 ( x : y) execution

ios - 如何在 swift 中使用 NMSSH

ios - 可以将两个 iOS 应用程序与同一个 Firestore 数据库一起使用吗?

ios - 为 UITabBarController subview Controller 设置相同的导航栏?

c++ - 为什么 for 循环不能定义两个范围的变量?

ios - 查找 Xcode 项目的 ${PROJECT_DIR}

objective-c - iOS + jqueryMobile 无法在加载 html 文件时捕获 webview 事件

ios - "Initializer for conditional binding must have Optional type, not ' [字符串] '"