每次调用函数Swift 3时,移动到数组中的下一个元素

时间:2017-06-21 05:10:32

标签: ios arrays swift

我有一个包含5个图像的数组。每隔5秒钟,我希望每次调用nextImage()函数时都显示数组中的下一个元素。

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)
}

我被困在nextImage函数中,因为我对swift编程很新,并且会喜欢建议。感谢。

6 个答案:

答案 0 :(得分:3)

从数组中获取当前图像的索引并增加1.如果数组索引不包含下一图像索引,则使用第0个图像。如果imageview没有任何图像显示第0张图像。试试这个。

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]
  }

答案 1 :(得分:0)

您需要一个变量来跟踪当前图像的索引,然后每次递增

var currentImage = -1

func nextImage() {
    currentImage = currentImage + 1
    if currentImage >= arrayPhoto.count {
        currentImage = 0
    }
    imageView.image = arrayPhoto[currentImage]
}

答案 2 :(得分:0)

声明preventFocusChange(e) { e.preventDefault(); }

var i = 0

答案 3 :(得分:0)

你想连续显示图像吗?如果没有,你必须考虑使时间无效。

var currentIndex = 0

func nextImage() {
   guard currentIndex < arrayPhoto.count else {
        timer.invalidate() //if you don't want to repeat showing the images you can invalidate the timer.
        currentIndex = 0 // add this if you want to repeat showing the image
        return 
   }
   imageView.image = arrayPhoto[currentIndex]
   currentIndex += 1
 }

答案 4 :(得分:0)

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]

答案 5 :(得分:0)

使用iterator.advanced(by :)函数

var curIdx = arrayPhoto.startIndex

func next() -> UIImage {
    curIdx = curIdx.advanced(by: 1) 
    curIdx = curIdx > arrayPhoto.endIndex ? arrayPhoto.startIndex : curIdx
    return arrayPhoto[curIdx]
}

func prev() -> UIImage {
    curIdx = curIdx.advanced(by: -1) 
    curIdx = curIdx < arrayPhoto.startIndex ? arrayPhoto.endIndex : curIdx
    return arrayPhoto[curIdx]
}