有没有更快的方法来检测UIScrollView的contentOffset / UIPickerView如何在高速时触发反馈?

问题描述 投票:0回答:1

我有一个水平滚动的UICollectionView来模仿iOS的UIPickerView。现在,我希望在选择更改时触发触觉反馈,就像UIPickerView一样。

问题是当你以高速滚动时,scrollViewDidScroll的调用速度不够快。

目前,我正在检查集合视图的x偏移量并在x偏移量是单元格宽度(12pt)的倍数时触发触觉反馈,但是当x偏移量跳跃超过12时,将跳过反馈。

uiscrollview uicollectionview uipickerview uiscrollviewdelegate
1个回答
0
投票

当偏移量是单元格宽度的精确倍数时,不要试图提供反馈,而是在“当前单元格”发生变化时提供反馈。

保留“当前单元格”(索引)类级变量:

var currentCellIndex: Int = 0

let cellWidth: CGFloat = 12.0  // or however you get it

在滚动时,获取“新”单元格:

    let newCellIndex: Int = Int(scrollView.contentOffset.x / cellWidth)

    if newCellIndex != currentCellIndex {
        // provide feedback
        currentCellIndex = newCellIndex
    }

所以,一开始,contentOffset.x将等于0,而currentCellIndex将是0。当用户滚动(非常非常慢)时,您将获得:

Int( 1.0 / 12.0) // equals 0, no change
Int( 2.0 / 12.0) // equals 0, no change
Int( 3.0 / 12.0) // equals 0, no change
Int( 4.0 / 12.0) // equals 0, no change
etc ...
Int(12.0 / 12.0) // equals 1, so newIndex != curIndex... provide feedback and update curIndex
Int(13.0 / 12.0) // equals 1, no change
Int(14.0 / 12.0) // equals 1, no change
Int(15.0 / 12.0) // equals 1, no change
Int(16.0 / 12.0) // equals 1, no change
etc ...
Int(24.0 / 12.0) // equals 2, so newIndex != curIndex... provide feedback and update curIndex

当用户快速滚动时:

Int( 9.0 / 12.0) // equals 0, no change
Int(16.0 / 12.0) // equals 1, so newIndex != curIndex... provide feedback and update curIndex
Int(31.0 / 12.0) // equals 2, so newIndex != curIndex... provide feedback and update curIndex
Int(64.0 / 12.0) // equals 5, so newIndex != curIndex... provide feedback and update curIndex
etc ...
© www.soinside.com 2019 - 2024. All rights reserved.