ios - 如何跟踪 UICollectionView 索引

标签 ios swift variables uicollectionview

我想在我的代码中使用一个变量来跟踪我的 UICollectionView 的索引,但我无法让它工作。经过一些故障排除后,我将代码归结为以下内容,如果将其粘贴到空的 viewController 中应该可以工作,因为不涉及 Storyboard 。动画 gif 说明了这个问题。最初我的变量“selectedItem”等于反射(reflect) data = [0,1,2,3] 的 UICollectionView Cell 文本,但是当我向右滑动时,它立即变为 1。然后它保持 1,直到它再次匹配的最后一个单元格。倒车时重复该模式。感谢您的帮助——

ViewController

import UIKit

class CodeCollView2: UIViewController, UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
  var data = [0,1,2,3] //["0", "1", "2", "3" ]
  let cellId = "cellId2"

  var selectedItem = 0

  lazy var cView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    layout.minimumLineSpacing = 0
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.isPagingEnabled = true
    cv.dataSource = self
    cv.delegate = self
    return cv
  }()

  var indexLabel: UILabel = {
    let label = UILabel()
    label.text = ""
    label.font = UIFont.systemFont(ofSize: 30)
    return label
  }()

  override func viewDidLoad() {
    super.viewDidLoad()
    setupViews()
  }

  func setupViews() {
    cView.register(CCell2.self, forCellWithReuseIdentifier: cellId)
    view.addSubview(cView)
    cView.translatesAutoresizingMaskIntoConstraints = false
    cView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    cView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    cView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    cView.heightAnchor.constraint(equalToConstant: 200).isActive = true
    view.addSubview(indexLabel)
    indexLabel.translatesAutoresizingMaskIntoConstraints = false
    indexLabel.bottomAnchor.constraint(equalTo: cView.topAnchor).isActive = true
    indexLabel.centerXAnchor.constraint(equalTo: cView.centerXAnchor).isActive = true
  }

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

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CCell2
    selectedItem = indexPath.item
    indexLabel.text = "seletedItem = \(selectedItem)"
    cell.itemValue = data[selectedItem]
    return cell
  }

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return collectionView.frame.size
  }
}

//============== CVCell ==================
class CCell2: UICollectionViewCell {

  var itemValue: Int? {
    didSet {
      if let val = itemValue {
        itemLabel.text = "\(val)"
      }
    }
  }

  var itemLabel: UILabel = {
    let label = UILabel()
    label.font = UIFont.systemFont(ofSize: 100)
    return label
  }()

  override init(frame: CGRect) {
    super.init(frame: frame)
    backgroundColor = .lightGray
    addSubview(itemLabel)
    itemLabel.translatesAutoresizingMaskIntoConstraints = false
    itemLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    itemLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

最佳答案

作为Nikita's answer提到,cellForItemAt 在要显示一个单元格时被调用,即使您只看到它的一部分并返回到上一个单元格,所以您不应该使用它来决定单元格在什么位置中心。

scrollViewDidScroll 是跟踪您位于中心的单元格的正确方法,您可以使用如下内容打印您所在的索引:

    func scrollViewDidScroll(_ scrollView:UIScrollView)
    {
        let midX:CGFloat = scrollView.bounds.midX
        let midY:CGFloat = scrollView.bounds.midY
        let point:CGPoint = CGPoint(x:midX, y:midY)

        guard

           let indexPath:IndexPath = collectionView.indexPathForItem(at:point)

        else
        {
           return
        }

        let currentPage:Int = indexPath.item
        indexLabel.text = "seletedItem = \(currentPage)"
    }

关于ios - 如何跟踪 UICollectionView 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45446448/

相关文章:

ios - Xcode 11.3 beta 如何在 UITableview 中导航到顶部

ios - 如何将图像加载到 iOS 应用程序中

variables - 通过 Ansible "terraform"模块执行 Terraform。需要一组字符串

ios - 如何获取已通过 snapkit 设置的 UIView 的框架

ios - 功能需要来自 plist 的权利可能无法运行 Xcode 6.1

swift - 暂停和重新启动动画

swift - 如何在 BehaviorRelay 中编辑当前值的属性?

ios - 如何使用静态自身实例将模型类保存在 UserDefaults 中?

java - 成员变量和局部方法变量可以重名吗?

用于检查/分配变量的 c# 习语