我正在尝试使用swift将滑动手势识别器添加到集合视图中。每次用户向右或向左滑动时,我都希望我的集合视图重新加载。但是,当我在模拟器上向右或向左滑动集合视图时,它会给我一个错误,AppDelegate.swift类会自动打开。错误说“libc ++ abi.dylib:以NSException类型的未捕获异常终止”
我将此部分写入collectionViewController类
中的viewDidLoad() collectionView.userInteractionEnabled = true
collectionView.delegate = self
var left = UISwipeGestureRecognizer(target: collectionView, action: "swipping:")
left.direction = UISwipeGestureRecognizerDirection.Left
collectionView.addGestureRecognizer(left)
var right = UISwipeGestureRecognizer(target: collectionView, action: "swipping:")
right.direction = UISwipeGestureRecognizerDirection.Right
collectionView.addGestureRecognizer(right)
这是翻转功能:
func swipping (gesture : UIGestureRecognizer){
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Left:
collectionView.reloadData()
pageControl.currentPage++
case UISwipeGestureRecognizerDirection.Right:
collectionView.reloadData()
pageControl.currentPage--
default:
break
}
}
}
将UIGestureRecognizerDelegate添加到CollectionViewController类和AppDelegate类。我该怎么办?
感谢。
答案 0 :(得分:2)
声明手势识别器时,将collectionView指定为目标:
var left = UISwipeGestureRecognizer(target: collectionView, action: "swipping:")
但我相信swiping:方法放在声明发生的同一个文件中。 你必须将目标改为自我:
var left = UISwipeGestureRecognizer(target: self, action: "swipping:")
var right = UISwipeGestureRecognizer(target: self, action: "swipping:")
//扩展
这不起作用,因为UICollectionView是UIScrollView的子类,当您滑动UIScrollView处理手势时(这是因为您可以在水平方向创建集合,因此集合视图需要知道您向左/向右滚动)。
您应该考虑覆盖UIScrollViewDelegate方法:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
找出滑动,你应该处理它而不是添加手势识别器。
尝试类似的东西:
//Declare private property
@property (nonatomic, assign) CGFloat prevOffset
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (self.prevOffset > scrollView.contentOffset.x)
// You are swiping right
else if (self.prevOffset < scrollView.contentOffset.x)
// You are swiping left
self.prevOffset = scrollView.contentOffset.x;
}