如何在集合视图中添加声音反馈,例如选择视图?



嗨,我正在尝试在滚动浏览集合视图项目时添加反馈。我应该在哪里添加集合视图委托中的反馈代码。如果我添加 willDisplay,然后添加最初将显示的单元格将调用反馈,这不好。仅当用户滚动并选择项目时,我才需要提供反馈。

假设您只向一个方向(如垂直)滚动,并且所有项目行的高度相同,则可以使用scrollViewDidScroll(_:)来检测 UIPickerView 等选择。

class ViewController {
var lastOffsetWithSound: CGFloat = 0
}
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let flowLayout = ((scrollView as? UICollectionView)?.collectionViewLayout as? UICollectionViewFlowLayout) {
let lineHeight = flowLayout.itemSize.height + flowLayout.minimumLineSpacing
let offset = scrollView.contentOffset.y
let roundedOffset = offset - offset.truncatingRemainder(dividingBy: lineHeight)
if abs(lastOffsetWithSound - roundedOffset) > lineHeight {
lastOffsetWithSound = roundedOffset
print("play sound feedback here")
}
}
}
}

请记住,UICollectionViewDelegateFlowLayout继承UICollectionViewDelegate,而本身继承UIScrollViewDelegate,因此您可以在其中任何一个中声明scrollViewDidScroll

您可以在视图控制器方法中添加它

touchesBegan(_:with:)
touchesMoved(_:with:)

因此,每当用户在任何地方与您的视图控制器交互时,您都可以提供反馈,并且它仅限于用户交互,而不是当您以编程方式添加单元格或在表视图上调用更新时。

如果控制器中还有其他 UI 组件,并且希望将反馈限制为集合视图而不是其他组件,则可以在这些方法中检查视图。

let touch: UITouch = touches.first as! UITouch
if (touch.view == collectionView){
println("This is your CollectionView")
}else{
println("This is not your CollectionView")
}

不要忘记调用 super,让系统有机会对方法做出反应。 希望这有帮助。

最新更新