[英]iOS - TapGestureRecognizer - Tap is applicable for the whole screen not for a view
[英]Not able to register a tap on the screen using tapGestureRecognizer
我正在尝试使用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()
}
}
尝试通过更新选择器方法将整个视图的endEditing设置为true:
@objc func tableViewTapped (){
view.endEditing(true)
}
另外,您可能希望添加而不是tableView
而不是tableView
来view
手势本身,因为与didSelectRowAt
方法重叠可能会引起进一步的问题。
如果这样不起作用,请尝试在viewDidLoad
添加以下内容(在这种情况下,您将不需要gestureRecognizer
):
messageTableView.keyboardDismissMode = .interactive
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.