2016-11-21 24 views
0

我有UITableView與嵌入UICollectionView。在第一部分中有用UITextField定製的單元格,第二部分有UICollectionView。UITableView中的UICollectionView不檢測tap因爲view.addGestureRecognizer()

要隱藏鍵盤,當用戶敲擊的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) 
} 

回答

0

僅當鍵盤出現時才添加手勢識別器,並在您關閉鍵盤時將其移除。