Swift从数组

时间:2016-08-31 09:08:35

标签: ios arrays swift uiimage

尝试添加从外部阵列中随机选择的背景图像。随机函数正在运行,但它没有将值注入后台UIImage。

代码是:

    let chooseImage = images.BackgroundImages
    let randomImage = chooseImage.sample()

    backgroundImage.image = UIImage(named: randomImage)
    print(randomImage)

打印确实显示正确的值,我在UIImage中尝试了“(randomImage)”。

编辑:如果我添加“(randomImage).jpg”然后代码按预期工作,但会快速推断设备上的每种类型,即@ 2x,@ 3x等。我是否需要使用资产名称?

由于

4 个答案:

答案 0 :(得分:0)

    //in case of arrImage has UIImages

    if arrImage.count > 0 {
        let randomIndex = random() % arrImage.count
        let randomImage = arrImage.objectAtIndex(randomIndex) as! UIImage
    }else{
        let randomImage = placeholderImage
    }

    //in case of arrImage has Strings

    if arrImage.count > 0 {
        let randomIndex = random() % arrImage.count
        let randomString = arrImage.objectAtIndex(randomIndex) as! String
        let randomImage = UIImage(name:randomString)
    }else{
        let randomImage = placeholderImage
    }

答案 1 :(得分:0)

它成功运行。当您运行应用程序

时,它将始终为您提供不同的图像
   imageArr = ["1.jpeg","2.jpeg","3.jpeg","4.jpeg"]
    let RandomNumber = Int(arc4random_uniform(UInt32(self.imageArr.count)))
    //imageArr is array of images
     let image = UIImage.init(named: "\(imageArr[RandomNumber])")

    let imageView = UIImageView.init(image: image)

答案 2 :(得分:0)

您现在可以对符合Sequence的所有内容进行scoring

答案 3 :(得分:-1)

RandomNumber = Int(arc4random_uniform(UInt32(self.imageArr.count)))
//imageArr is array of images

imageArr[RandomNumber]

试试这个,你还需要帮助我。