gpt4 book ai didi

快速 6 个随机数到 tableViewCell 中的 6 个图像

转载 作者:行者123 更新时间:2023-11-30 14:12:34 24 4
gpt4 key购买 nike

我对 Swift 还很陌生,我找不到 Swift 问题的答案。

创建一个乐透号码生成器,我可以使用标签来完成它,但我在将这些数字映射到图像(例如乐透球图像)时遇到困难,因此每当填充数字时,它都会将这些数字转换为图像并显示在自定义单元格。

目前正在将 tableView 与客户单元一起使用 - 我在一个单元中有六个 UIImageView

在我的实践中,我发现自己在重复相同的代码。例如ball1.image = arc4Random_uniform(45) 和 ball2 ball3 等等..想要学习更难的方法。我的意思是不重复代码。请大师如何填充 1-45 的 6 个数字而不重复并在单元格中显示 6 个乐透球图像?

最佳答案

为了减少代码使用,请在 View Controller 上创建方法并使用 ImageView 数组调用它。方法如下:

func setImages(imageViews: [UIImageView]) {
var numSet = Set<Int>()
while numSet.count < imageViews.count
{
numSet.insert(Int(arc4random_uniform(45)) + 1) // Assuming you want numbers from 1 to 45 inclusive of both.
}
for (i, elem) in numSet.sort(<).enumerate() // Don't use sort if not needed.
{
imageViews[i].image = UIImage(named: "lotto\(elem).png") // Or whatever naming convention you used for the images.
}
}

只需使用 imageViews 数组调用 setImages 即可。它使用数组的计数来生成足够的数字。不要忘记更改图像使用的命名方案。我假设您使用了lotto1.png、lotto2.png ... lotto44.png 的命名方案

关于快速 6 个随机数到 tableViewCell 中的 6 个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31603628/

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