简体   繁体   English

为什么我的Swift代码不起作用?

[英]Why Isn't my Swift code working?

I have written a piece of code in my app which is supposed to generate a random number from 1-10 and my images are all named 1-10. 我在我的应用程序中编写了一段代码,该代码应该从1-10生成一个随机数,并且我的图像都命名为1-10。 It then is supposed to display that image on the screen in a UIImageView. 然后应该在UIImageView中在屏幕上显示该图像。 Here is my code: 这是我的代码:

import UIKit
import Foundation

class ViewController: UIViewController {
    @IBOutlet var QuoteImage: UIImageView!

    func randomImagePicker() {
        var QuoteImages: [UIImage] {
            var QuoteImages: [UIImage] = []
            // Create images named 1 - 10
            let randomImageIndex = Int(arc4random_uniform(10) + 1)
            // Assign the image property of the imageView to the element behind the random index in the images array
            self.QuoteImage.image = QuoteImages[randomImageIndex]
            let image = UIImage(named: "\(randomImageIndex)")!
            QuoteImages.append(image)
            // Create a random index
            return QuoteImages
        }
    }
}

I'd suggest simply getting the index and then setting the image property of the image view accordingly: 我建议只获取索引,然后相应地设置图像视图的image属性:

class ViewController: UIViewController {
    @IBOutlet var quoteImageView: UIImageView!

    func randomImagePicker() {
        let index = Int(arc4random_uniform(10) + 1)
        quoteImageView.image = UIImage(named: "\(index)")!
    }
}

If you need the array for some other purpose, explain what your intent was and we can clarify how you might achieve that. 如果您出于其他目的需要该阵列,请说明您的意图,我们可以阐明您可能如何实现。 But if you're just trying to set the image of the image view to be some random image, the above should suffice. 但是,如果您只是试图将图像视图的image设置为随机图像,则上面的内容就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM