我正在尝试使用Firebase构建聊天应用程序。我试图实现轻击手势,以便在打开键盘时将其解开。不幸的是,当您点击屏幕时,什么也不会发生。我尝试了不同的事情,结果相同。如果有人知道它不起作用的原因,我将不胜感激。我也尝试使用参数numberOfTouches,结果相同。
class ChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
// Declare instance variables here
// We've pre-linked the IBOutlets
@IBOutlet var heightConstraint: NSLayoutConstraint!
@IBOutlet var sendButton: UIButton!
@IBOutlet var messageTextfield: UITextField!
@IBOutlet var messageTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
messageTableView.delegate = self
messageTableView.dataSource = self
//TODO: Set yourself as the delegate of the text field here:
messageTextfield.delegate = self
//TODO: Set the tapGesture here:
//messageTableView.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tableViewTapped))
messageTableView.addGestureRecognizer(tapGesture)
//TODO: Register your MessageCell.xib file here:
messageTableView.register(UINib(nibName: "MessageCell", bundle: nil), forCellReuseIdentifier: "customMessageCell")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customMessageCell", for: indexPath) as! CustomMessageCell
let messageArray = ["1","2","3"]
cell.messageBody.text = messageArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension
return 3
}
@objc func tableViewTapped (){
messageTableView.endEditing(true)
}
func textFieldDidBeginEditing(_ textField: UITextField) {
UIView.animate(withDuration: 0.5) {
self.heightConstraint.constant = 380
self.view.layoutIfNeeded()
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
UIView.animate(withDuration: 0.5) {
self.heightConstraint.constant = 50
self.view.layoutIfNeeded()
}
}
答案 0 :(得分:0)
尝试通过更新选择器方法将整个视图的endEditing设置为true:
@objc func tableViewTapped (){
view.endEditing(true)
}
此外,您可能希望将手势识别器添加到view
本身而不是tableView
上,因为它可能会由于与didSelectRowAt
方法重叠而引起更多问题。
如果这样不起作用,请尝试在您的viewDidLoad
中添加以下内容(在这种情况下,您将不需要gestureRecognizer
)
messageTableView.keyboardDismissMode = .interactive