在 UICollectionView 滚动后获取可见项的更新 IndexPath

Den*_*nov 1 uiscrollview ios uicollectionview swift

我有一个不同时期(每天)的 collectionView 供用户选择。每个项目的大小等于 collectionView 本身的大小。

@IBOutlet weak var periodCollectionView: UICollectionView!
@IBOutlet weak var itemLabel: UILabel!

let collectionValues = ["Day", "Week", "Month", "Year"]
var currentVisibleItem: Int?

override func viewDidLoad() {
    super.viewDidLoad()

}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PeriodName", for: indexPath) as? DisplayPeriodCollectionViewCell
    else {
        fatalError("Unable to cast collection view cell as DisplayPeriodCollectionViewCell")
    }

    cell.periodName.text = collectionValues[indexPath.item]

    return cell

}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let height = collectionView.frame.height
    let width = collectionView.frame.width

    return CGSize(width: width, height: height)
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是获取一个信息标签,以在 collectionView 滚动后显示当前可见项的索引。她是代码:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let centerPoint = CGPoint(x: periodCollectionView.center.x + periodCollectionView.contentOffset.x, y: 1.0)
    print("centerPoint: \(centerPoint)")

    if let currentItemIndexPath = periodCollectionView.indexPathForItem(at: centerPoint) {
        currentVisibleItem = currentItemIndexPath.item
        print("index of current item: \(currentVisibleItem!)")
        itemLabel.text = "\(currentVisibleItem!)"
    } else {
        print("could not get index of current item...")
    }

}
Run Code Online (Sandbox Code Playgroud)

我添加了打印语句来检查在运行时是否正确定义了值,并且它们显示一切正常。问题是标签在滚动结束后并不总是更新其文本,而是等待新的滚动发生:

在此处输入图片说明

我无法弄清楚为什么会发生这种情况 - 在scrollViewDidEndDecelerating表明所有代码都被执行时设置断点,那么标签文本有什么问题?

更新。不更新标签文本似乎是模拟器问题 - 在设备上运行时,标签更新正确。

Den*_*vin 5

尝试这个

override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let currentIndex = scrollView.contentOffset.x / CGFloat((itemWidth + interitemSpacing / 2))
    print(currentIndex)
}
Run Code Online (Sandbox Code Playgroud)