dimanche 8 mai 2016

Random image code inside animation swift code

I have tried several codes I have found here (stackoverflow) and on web, but no one of them worked.

Can you please help?

This is code:

        import UIKit

class ViewController: UIViewController {
@IBOutlet weak var UmagGlavna: UIImageView!

let images = [
    UIImage(named: "UmagGlavna1")!,
    UIImage(named: "UmagGlavna2")!,
    UIImage(named: "UmagGlavna3")!]

var index = 0
let animationDuration: NSTimeInterval = 0.4
let switchingInterval: NSTimeInterval = 5

override func viewDidLoad() {
    super.viewDidLoad()

    UmagGlavna.image = images[index]
    index += 1
    animateImageView()
}

func animateImageView() {
    CATransaction.begin()

    CATransaction.setAnimationDuration(animationDuration)
    CATransaction.setCompletionBlock {
        let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(self.switchingInterval * NSTimeInterval(NSEC_PER_SEC)))
        dispatch_after(delay, dispatch_get_main_queue()) {
            self.animateImageView()
        }
    }

    let transition = CATransition()
    transition.type = kCATransitionFade
    /*
     transition.type = kCATransitionPush
     transition.subtype = kCATransitionFromRight
     */
    UmagGlavna.layer.addAnimation(transition, forKey: kCATransition)
    UmagGlavna.image = images[index]

    CATransaction.commit()

    index = index < images.count - 1 ? index + 1 : 0
}

}

I have try to insert this line in func viewDidLoad

UmagGlavna.image = UIImage(named: "UmagGlavna\(arc4random_uniform(3) + 1)")

then I have also try to insert several other codes, this one was one of them:

        @IBAction func randomimage(sender: AnyObject) {
//list of Images in array 
let image : NSArray = [
    UIImage(named: "UmagGlavna1")!,
    UIImage(named: "UmagGlavna2")!,
    UIImage(named: "UmagGlavna3")!]

//random image generating method
let imagerange: UInt32 = UInt32(images.count)
let randomimage = Int(arc4random_uniform(imagerange))
let generatedimage: AnyObject = images.objectAtIndex(randomimage)
self.myimage.image = generatedimage as? UIImage

}

And some other codes, but nothing has made images load random.

What I need is to first image load (or all images) random, because when you start app, I don't wont always to load with same (first) image.

Thank is advance for help. :)




Aucun commentaire:

Enregistrer un commentaire