我有带有嵌入式 UICollectionView 的 UITableView。在第一部分中,有带有 UITextField 的自定义单元格,在第二部分中有 UICollectionView。
当用户点击我正在使用的 UITextField 外部时隐藏键盘
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)
func dismissKeyboard(sender: UIGestureRecognizer) {
view.endEditing(true)
}
正因为如此,正如我所发现的,我的 UICollectionView 无法识别其项目上的点击。如果我删除 view.addGestureRecognizer(tap) 一切正常,但键盘在这种情况下不会隐藏。
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder() //if desired
return true
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileTableViewCell", for: indexPath) as! ProfileTableViewCell
cell.value.delegate = self // value is my textField
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "WallpaperTableViewCell", for: indexPath) as! WallpaperTableViewCell
cell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, index: (indexPath as NSIndexPath).row)
return cell
default:
let cell = UITableViewCell()
return cell
}
}
如何解决此问题并在 UICollectionView 中同时使用隐藏键盘和点击识别? 谢谢
为了将 UICollectionView 嵌入到 UITableView 中,我使用了这个示例 https://github.com/DahanHu/DHCollectionTableView
UPD
感谢菲利普·米尔斯
答案非常简单
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
和
func keyboardWillShow(notification: NSNotification) {
view.addGestureRecognizer(tap)
}
func keyboardWillHide(notification: NSNotification) {
view.removeGestureRecognizer(tap)
}
最佳答案
仅在键盘出现时添加手势识别器,并在键盘消失时将其删除。
关于swift - UITableView 中的 UICollectionView 由于 view.addGestureRecognizer() 未检测到点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40726905/