iOS:向容器视图添加UITapGestureRecognizer拦截UICollectionView的didSelectItemAtIndexPath方法

时间:2014-12-27 03:17:18

标签: ios swift uicollectionview uitapgesturerecognizer

我在我的ViewController中向我的主UITapGestureRecognizer添加了Content View,以便在点按内容视图时关闭我的键盘。

问题是我的内容视图中有UICollectionView,并设置UITapGestureRecognizer拦截了UICollectionView的点按。

如何允许我的UICollectionView点按,以便didSelectItemAtIndexPath方法再次触发?

func setupGestureRecognizer() {
    let dismissKeyboardTap = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
    contentView.addGestureRecognizer(dismissKeyboardTap)
}

func dismissKeyboard() {
    contentView.endEditing(true)
}

2 个答案:

答案 0 :(得分:16)

解决此问题的方法是在您的.cancelsTouchesInView = false中添加 UITapGestureRecognizer

这允许其他视图中的触摸通过,例如UITableViewCell触摸。

func setupGestureRecognizer() {
    let dismissKeyboardTap = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
    dismissKeyboardTap.cancelsTouchesInView = false
    contentView.addGestureRecognizer(dismissKeyboardTap)
}

func dismissKeyboard() {
    contentView.endEditing(true)
}

答案 1 :(得分:0)

试试这个

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}  

并删除你的tapGesture。