Swift获取当前显示的索引UICollectionView

时间:2017-06-10 16:59:36

标签: ios swift uicollectionview carousel

我正在为ios制作音乐播放器。我有一个音乐列表和一个详细视图,您可以左右滑动以更改歌曲。问题是我无法让当前显示的元素播放合适的歌曲,但显示的图像很好。我想知道如何在Carousel视图中获取当前元素,因为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) {

}  
}

1 个答案:

答案 0 :(得分:2)

要在集合视图中获取当前显示的单元格,您可以访问visibleCells UICollectionView属性。 Documentation

您也可以使用indexPathsForVisibleItems来获取indexPaths。 Documentation

然后,还有indexPath(for:)来获取您引用的单元格的indexPath,例如visibleCells的结果。 Documentation