I have an array of 5 images. After every 5 seconds, I wish to display the next element in the array every time it calls the nextImage() function.
var timer = Timer()
var arrayPhoto: [UIImage] = [
UIImage(named: "1.jpg"!,
UIImage(named: "2.jpg"!,
UIImage(named: "3.jpg"!,
UIImage(named: "4.jpg"!,
UIImage(named: "5.jpg"!,
]
func nextImage() {
// Displays 1.jpg when it first goes into the nextImage() function
// Subsequently, to display 2.jpg the second time it goes into nextImage() function.
// Repeat this till the end of the array.
// If end of array, move to the start.
}
override func viewDidLoad() {
timer = Timer.scheduledTimer(TimeInterval: 5, target: self, selector: (#selector(nextImage)), userInfo: nil, repeats: true)
}
I am stuck at the nextImage function as I am very new to swift programming and would appreciate advice. Thanks.
Get index of current Image from array and increment 1. If array indices doesn't contains next image index use 0th image. If imageview doesn't have any images show 0th image. Try this.
func nextImage()
{
let currentIndex = arrayPhoto.index(of: imageView.image ?? UIImage()) ?? -1
var nextIndex = currentIndex+1
nextIndex = arrayPhoto.indices.contains(nextIndex) ? nextIndex : 0
imageView.image = arrayPhoto[nextIndex]
}
My solution on Swift 4.2:
Next element:
let currentIndex = songPlaylist.index(of: selectedSong ?? Song()) ?? -1
var nextIndex = currentIndex + 1
nextIndex = songPlaylist.indices.contains(nextIndex) ? nextIndex : 0
selectedSong = songPlaylist[nextIndex]
Previous element:
let currentIndex = songPlaylist.index(of: selectedSong ?? Song()) ?? -1
var nextIndex = currentIndex - 1
nextIndex = songPlaylist.indices.contains(nextIndex) ? nextIndex : songPlaylist.count - 1
selectedSong = songPlaylist[nextIndex]
You need a variable to keep track of current image's index, then increment it every time
var currentImage = -1
func nextImage() {
currentImage = currentImage + 1
if currentImage >= arrayPhoto.count {
currentImage = 0
}
imageView.image = arrayPhoto[currentImage]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With