UICollectionView检测滚动方向并更改图像

时间:2018-09-27 19:08:24

标签: ios swift uiscrollview uicollectionview

我正在使用UICollectionView创建类似于Tinder Swipe的滑动。 当用户在显示新页面(卡片)之前开始拖动时,我想检测滚动方向。检测到它时,应将图像设置为“竖起大拇指”(向右滑动)或“竖起大拇指”(向左滑动)。

现在,我使用scrollViewWillBeginDragging,它几乎可以与contentOffset进行比较,但这不是我想要的,因为它显示图像的时间很晚。

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate{

    var imageArray = [UIImage(named: "profil"), UIImage(named: "profil"),UIImage(named: "profil"),UIImage(named: "profil"),UIImage(named: "profil"),UIImage(named: "profil"),UIImage(named: "profil")]

    @IBOutlet weak var thumbImage: UIImageView!
    var currentPage = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageArray.count
    }

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

        cell.imgImage.image = imageArray[indexPath.row]
        cell.backgroundColor = indexPath.item % 2 == 0 ? .red : .green

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
    } 


    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {

        var page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)

        if(page > currentPage)
        {
            thumbImage.isHidden = false
            thumbImage.image = #imageLiteral(resourceName: "thumbsup")
            print("RIGHT")
        } else {
            thumbImage.isHidden = false
            thumbImage.image = #imageLiteral(resourceName: "thumbsdown")
            print("LEFT")
        }

        currentPage = page

    }
}

1 个答案:

答案 0 :(得分:0)

在当前的实现中,仅当页面更改时才显示拇指图像,即当滑动一半时。我将页面更改与拇指显示分开。伪代码:

  if(currentOffset> lastOffset){
    showThumbsUp()
}
其他{
    showThumbsDown()
}

页面= ...
if(page!= currentPage){
    changePage(页面)
    lastOffset = currentOffset
}