[英]collectionView's didSelectItemAt not called when use it with UITapGestureRecognizer
Once I use addGestureRecognizer to dismiss keyboard in scrollView, collectionView's didSelectItemAt would not work. 一旦我使用addGestureRecognizer来关闭scrollView中的键盘,collectionView的didSelectItemAt将无法工作。 Any suggestions?
有什么建议么?
UPDATE CODE: Currently I can tap to dismiss keyboard and tap to do something with collection cell. 更新代码:目前,我可以点击以关闭键盘,然后点击以对收集单元执行某些操作。 But, if I swipe the scrollView, the keyboard will dismiss.
但是,如果我滑动scrollView,键盘将关闭。 Any way to prevent that?
有什么办法可以防止?
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
}
}
Try to implement UIGestureRecognizerDelegate
. 尝试实现
UIGestureRecognizerDelegate
。 Implement its gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:)
method in your code to return true
- that way your gesture recognizer will work, but it will also allow other gestures to be recognized (specifically the one in the collectionView
). 实施其
gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:)
方法在你的代码返回true
-这样你的手势识别的工作,但它也将允许其他手势识别(特别是一个在collectionView
)。
Code: 码:
// add this to initializing code to set gesture recognizer's delegate to self
tapViewGesture.delegate = self
Delegate implementation: 委托实现:
extension YourViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
Don't use a gesture recognizer. 不要使用手势识别器。 That is intercepting your taps and not giving them to the collection view.
那是在拦截您的水龙头,而不是让它们进入收藏视图。 Instead put your call to
view.endEditing(true)
in the collectionView(_:didSelectItemAt:)
method. 而是将您的调用放在
collectionView(_:didSelectItemAt:)
方法中的view.endEditing(true)
上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.