简体   繁体   中英

Swift - change image of UIImageView dynamically

I have a normal UIImage and a list of images. My goal is that every few seconds the image changes automatically with some sort of never ending loop through my imageList .

This is my list:

let images: [UIImage] = [
        UIImage(named: "avocadoImage")!,
        UIImage(named: "beerImage")!,
        UIImage(named: "bikeImage")!,
        UIImage(named: "christmasImage")!,
        UIImage(named: "dressImage")!,
        UIImage(named: "giftImage")!,
        UIImage(named: "goalImage")!,
        UIImage(named: "rollerImage")!,
        UIImage(named: "shirtImage")!,
        UIImage(named: "shoeImage")!,
        UIImage(named: "travelImage")!,     
    ]

I tried this:

 NSTimer(timeInterval: 0.5, target: self, selector: "ChangeImage", userInfo: nil, repeats: true)

But I don't know how I can loop through my array over and over again.

Create the following instance properties:

private let imageView = UIImageView()
private var imageTimer: Timer?
private let images = [
    UIImage(named: "avocadoImage"),
    UIImage(named: "beerImage"),
    UIImage(named: "bikeImage"),
    UIImage(named: "christmasImage"),
    UIImage(named: "dressImage"),
    UIImage(named: "giftImage"),
    UIImage(named: "goalImage"),
    UIImage(named: "rollerImage"),
    UIImage(named: "shirtImage"),
    UIImage(named: "shoeImage"),
    UIImage(named: "travelImage"),
]

Then start the timer and add it to the run loop (likely viewDidLoad ):

private func startImageTimer() {
    imageTimer = Timer(fire: Date(), interval: 5, repeats: true) { (timer) in
        imageView.image = images.randomElement()
    }

    RunLoop.main.add(imageTimer!, forMode: .common)
}

Then you'll want to observe when the app enters and exits the background so you can toggle the timer. Add these observers (likely viewDidLoad ):

NotificationCenter.default.addObserver(self, selector: #selector(backgroundHandler), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(foregroundHandler), name: UIApplication.willEnterForegroundNotification, object: nil)

@objc private func backgroundHandler() {
    imageTimer?.invalidate()
    imageTimer = nil
}

@objc private func foregroundHandler() {
    startImageTimer()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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