您好,我正试图在滚动浏览集合视图项目时添加反馈。我应该在集合视图委托中添加反馈代码的位置。如果我添加willDisplay,那么添加最初显示的单元格将调用反馈,这是不好的。我只需要提供反馈时,用户滚动并选择一个项目。
发布于 2019-05-21 14:45:49
假设您只在一个方向上滚动(比如垂直滚动),并且所有行的项目都具有相同的高度,那么您可以使用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
。
发布于 2019-05-21 14:41:50
您可以将其添加到视图控制器方法中
touchesBegan(_:with:)
touchesMoved(_:with:)
因此,当用户在任何地方与视图控制器交互时,您都可以提供反馈,并且它将仅限于用户交互,而不是当您程序化地添加单元格或在表视图上调用update时。
如果您的控制器中还有其他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,让系统有机会对这些方法做出反应。希望这能有所帮助。
https://stackoverflow.com/questions/56239357
复制