gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:02:09 25 4
gpt4 key购买 nike

我正在尝试在按下另一个按钮后将按钮动态添加到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com