一旦我使用addGestureRecognizer来解除scrollView中的键盘,collectionView的didSelectItemAt将无效。有什么建议吗?
更新代码:目前我可以点按以关闭键盘并点击以对收集单元格执行某些操作。但是,如果我滑动scrollView,键盘将解除。有什么方法可以阻止它吗?
class PostVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var colorCollectionView: UICollectionView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var titleTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let tapViewGesture = UITapGestureRecognizer(target: self, action: #selector(PostVC.didTapViewForDismissKeyboard))
scrollView.addGestureRecognizer(tapViewGesture)
tapViewGesture.delegate = self
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool{
view.endEditing(true)
return false
}
func didTapViewForDismissKeyboard(_ pressed: UIGestureRecognizer) {
view.endEditing(true)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("HIHI")
}
extension PostVC: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
答案 0 :(得分:1)
尝试实施UIGestureRecognizerDelegate
。在代码中实现其gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:)
方法以返回true
- 这样您的手势识别器将起作用,但它也将允许识别其他手势(特别是collectionView
中的手势)。
代码:
// add this to initializing code to set gesture recognizer's delegate to self
tapViewGesture.delegate = self
代表实施:
extension YourViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
答案 1 :(得分:0)
请勿使用手势识别器。这是拦截您的水龙头而不是将它们提供给集合视图。而是将您的view.endEditing(true)
方法调用collectionView(_:didSelectItemAt:)
。