Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move to next element in array every time it calls the function Swift 3

Tags:

arrays

ios

swift

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.

like image 923
Spiral1ng Avatar asked Jun 21 '17 05:06

Spiral1ng


3 Answers

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]
  }
like image 83
RajeshKumar R Avatar answered Nov 20 '22 08:11

RajeshKumar R


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]
like image 33
Zhanserik Avatar answered Nov 20 '22 08:11

Zhanserik


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]
}
like image 1
xhg Avatar answered Nov 20 '22 07:11

xhg