gpt4 book ai didi

ios - 如何正确使用计时器来错开向 subview 添加对象?

转载 作者:行者123 更新时间:2023-11-28 12:39:35 24 4
gpt4 key购买 nike

class ViewController: UIViewController {

let manImage = UIImage(named: "man.png")

let buttons = (0..<5).map({_ in UIButton()})

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

createButtons()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func createButtons() {
var pos = 25
for index in 0...4 {
delay(Double(arc4random_uniform(5)) + 5) {
self.buttons[index].setBackgroundImage(self.manImage, forState: .Normal)
self.buttons[index].translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.buttons[index])
self.view.addConstraint(NSLayoutConstraint(
item: self.buttons[index],
attribute: .Leading,
relatedBy: .Equal,
toItem: self.view,
attribute: .Leading,
multiplier: 1,
constant: CGFloat(pos)))
pos += 10
}

}
}

func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
}

我一直在使用一堆来自搜索的不同时间延迟示例代码,但所有代码都会导致某些按钮同时显示。来自代码行

延迟(双(arc4random_uniform(5))+ 5)

这不是说 for 循环的每次迭代之间至少延迟 5 秒吗?为什么要这样做?

谢谢。

最佳答案

类似于您的原始方法的解决方案可能是使每个连续按钮相对于前一个按钮的延迟。

func createButtons() {
var delayTime = 0.0
var pos = 25
for index in 0...4 {
delayTime = delayTime + Double(arc4random_uniform(5)) + 5
delay(delayTime) {
self.buttons[index].setBackgroundImage(self.manImage, forState: .Normal)
self.buttons[index].translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.buttons[index])
self.view.addConstraint(NSLayoutConstraint(
item: self.buttons[index],
attribute: .Leading,
relatedBy: .Equal,
toItem: self.view,
attribute: .Leading,
multiplier: 1,
constant: CGFloat(pos)))
pos += 10
}
}
}

关于ios - 如何正确使用计时器来错开向 subview 添加对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39797503/

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