gpt4 book ai didi

ios - 生成不重复的随机 UIImage

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

在我的应用程序项目中,我随机显示了 107 张图像,我设置了一个 for 循环,将所有图像放入一个数组中。然后我采用该数组并选择一个随机索引。该索引与图片相关联,然后当用户向左滑动时该图片会出现在屏幕上。我的问题是,我能否做到这一点,以便我的代码不会重复数组中的相同索引,直到随机选择所有索引(或关闭应用程序之前的数量)。这是我的代码

class ViewController: UIViewController {

var pictureArray: [String] = []
@IBOutlet weak var quoteImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()

for i in 0...107{
pictureArray.append("quote\(i).jpg")
print(pictureArray)
}

// Do any additional setup after loading the view, typically from a nib.
let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector (changeQuotes))
swipeRecognizer.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeRecognizer)
}

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

}
override var prefersStatusBarHidden: Bool{
return true
}


@objc func changeQuotes(){

let numberOfImages: UInt32 = 107
let randomIndex = Int(arc4random_uniform(UInt32(pictureArray.count)))
let imageName = "\(pictureArray[randomIndex])"
print(imageName)
quoteImage.image = UIImage(named: imageName)


}
}

感谢您的帮助!

最佳答案

随机刷新你的数组,然后一张一张地得到“排序”的图像。

extension Sequence {
func randomSorted() -> [Element] {
var result = Array(self)
guard result.count > 1 else { return result }

for (i, k) in zip(result.indices, stride(from: result.count, to: 1, by: -1)) {
let newIndex = Int(arc4random_uniform(UInt32(k)))
if newIndex == i { continue }
result.swapAt(i, newIndex)
}
return result
}
}

关于ios - 生成不重复的随机 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47066305/

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