UICollectionView 检测滚动方向和更改图像
Posted
技术标签:
【中文标题】UICollectionView 检测滚动方向和更改图像【英文标题】:UICollectionView Detecting Scroll direction and Changing Image 【发布时间】:2018-09-27 19:08:23 【问题描述】:我正在使用 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】:在您当前的实现中,拇指图像仅在页面发生变化时显示,即滑动到一半时。我会将页面更改与拇指显示分开。伪代码:
if (currentOffset > lastOffset)
showThumbsUp()
else
showThumbsDown()
page = ...
if (page != currentPage)
changePage(page)
lastOffset = currentOffset
【讨论】:
如何获取 currentOffset 和 lastOffset 的值? 您可以从 scrollView.contentOffset.x 获取当前偏移量,lastOffset 将是您维护的变量 使用 panGestureRecognizer 是解决这个问题的好主意吗? 你直接从 UIScrollView 获取偏移量,为什么需要访问手势识别器?以上是关于UICollectionView 检测滚动方向和更改图像的主要内容,如果未能解决你的问题,请参考以下文章
UICollectionView横向滚动,sectionHeader的问题