简体   繁体   English

Swift获取当前显示的索引UICollectionView

[英]Swift get current displayed index UICollectionView

I'm making a music player for ios. 我正在为iOS做音乐播放器。 I have a list of music and a detail view that you can swipe left and right to change the songs. 我有音乐列表和详细视图,您可以左右滑动来更改歌曲。 The problem is I can't get the current displayed element to play the appropriate song, but the image displayed are good. 问题是我无法使当前显示的元素播放适当的歌曲,但是显示的图像很好。 I would like to know how can I get the current element in the Carousel View, because cellForItemAt doesn't work, when I swipe right it gives me the 2 next indexes. 我想知道如何在“轮播视图”中获取当前元素,因为cellForItemAt不起作用,当我向右滑动时,它会给我2个下一个索引。

import UIKit
import AVFoundation

private let reuseIdentifier = "Cell"


class PhotoCarouselCollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet var collectionView: UICollectionView!

@IBAction func pause(_ sender: Any) {
    if audioPlayer.isPlaying == true{
        audioPlayer.pause()
    }
}
@IBAction func play(_ sender: Any) {
    if audioPlayer.isPlaying == false{
        audioPlayer.play()
    }
}

@IBAction func slider(_ sender: UISlider) {
    audioPlayer.volume = sender.value
}

private var photoSet = [
    Photo(name: "pendulum", song: "pendulum"),
    Photo(name: "martin", song: "doitright"),
    Photo(name: "kungs",song: "thisgirl"),
    Photo(name: "future",song: "future"),
]

var photo: Photo?
var currentPhoto: Int?

let scrollView = UICollectionView.self
var pageControl : UIPageControl = UIPageControl(frame: CGRect(x:50,y: 300, width:200, height:50))



override func viewDidLoad() {

    super.viewDidLoad()

    let swipeRight = UISwipeGestureRecognizer(target: self, action: Selector(("respondToSwipeGesture:")))
    swipeRight.direction = UISwipeGestureRecognizerDirection.right
    self.view.addGestureRecognizer(swipeRight)

    let swipeLeft = UISwipeGestureRecognizer(target: self, action: Selector(("respondToSwipeGesture:")))
    swipeLeft.direction = UISwipeGestureRecognizerDirection.left
    self.view.addGestureRecognizer(swipeLeft)

}

func respondToSwipeGesture(gesture: UIGestureRecognizer) {

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {


        switch swipeGesture.direction {
        case UISwipeGestureRecognizerDirection.right:
            print("Swiped right")
        case UISwipeGestureRecognizerDirection.down:
            print("Swiped down")
        case UISwipeGestureRecognizerDirection.left:
            print("Swiped left")
        case UISwipeGestureRecognizerDirection.up:
            print("Swiped up")
        default:
            break
        }


    }

    //pageControl.currentPage = {currentPhoto!}();


    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Register cell classes
    // self.collectionView!.register(PhotoCarouselCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    // Do any additional setup after loading the view.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return photoSet.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotoCarouselCollectionViewCell

    // Configure the cell
    let photo = photoSet[indexPath.row.advanced(by: currentPhoto!)]

    print(indexPath.row)
    //let photo =  photoSet[currentPhoto!]
    //let photo = photoSet[indexPath.row]\

 //GETTING THE MUSIC TO BE PLAYED
 do{
        let audioPath = Bundle.main.path(forResource: photoSet[indexPath.row].song, ofType: "mp3")
        try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
        audioPlayer.play()
    }
    catch{
        print ("ERROR")
    }


    cell.imageView.image = UIImage(named: photo.name)

    return cell
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

}  
}

To get the currently displayed cells in a collection view, you can access the visibleCells property of UICollectionView . 要在集合视图中获取当前显示的单元格,可以访问UICollectionViewvisibleCells属性。 Documentation 文档

You can also use indexPathsForVisibleItems to get the indexPaths instead. 您也可以使用indexPathsForVisibleItems来获取indexPaths。 Documentation 文档

Then, there is also indexPath(for:) to get the indexPath for a cell you have a reference to, such as from the result of visibleCells . 然后,还有indexPath(for:)来获取您具有引用的单元格的indexPath,例如从visibleCells的结果中。 Documentation 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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