要避免UITextView妨碍UICollectionViewCell被点击,可以尝试以下解决方法。
// 创建一个UITapGestureRecognizer手势识别器
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideTextView(_:)))
// 设置手势识别器的代理为当前视图控制器
tapGesture.delegate = self
// 将手势识别器添加到UICollectionView
collectionView.addGestureRecognizer(tapGesture)
// 实现手势识别器的回调方法
@objc func hideTextView(_ gesture: UITapGestureRecognizer) {
let location = gesture.location(in: collectionView)
if let indexPath = collectionView.indexPathForItem(at: location), let cell = collectionView.cellForItem(at: indexPath) as? YourCollectionViewCell {
// 在这里执行cell的点击处理逻辑
} else {
// 隐藏UITextView
yourTextView.isHidden = true
}
}
// 实现手势识别器的代理方法,让手势识别器与UITextView共存
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let touch = touches.first {
let location = touch.location(in: self.view)
if !yourTextView.frame.contains(location) {
yourTextView.isHidden = true
}
}
}
override func touchesEnded(_ touches: Set, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
if let touch = touches.first {
let location = touch.location(in: self.view)
if let indexPath = collectionView.indexPathForItem(at: location), let cell = collectionView.cellForItem(at: indexPath) as? YourCollectionViewCell {
// 在这里执行cell的点击处理逻辑
}
}
}
以上是两种常见的解决方法,你可以根据自己的需求选择其中一种实现在你的项目中。