Reputation: 2314
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.
Upvotes: 1
Views: 2682
Reputation: 12405
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()
}
Upvotes: 5