How to remove the dismiss keyboard action on tapping outside MDCTextField
Clash Royale CLAN TAG#URR8PPP
How to remove the dismiss keyboard action on tapping outside MDCTextField
I am trying to use an MDCTextField and a table view together. The MDCTextField
filters the table view, then the user should tap a cell and the keyboard should dismiss and the table view should be hidden. The issue is that the keyboard dismisses and the table view is hidden before the table view registers that a cell was tapped. How can I register that a cell was tapped before the MDCTextField
registers the tap?
MDCTextField
MDCTextField
1 Answer
1
I use this extension you can place in a helpers.swift file but this way you can use on any UIViewController
extension UIViewController
func hideKeyboardWhenTappedAround()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
@objc func dismissKeyboard()
view.endEditing(true)
To use it, on viewDidLoad() just add this self.hideKeyboardWhenTappedAround()
self.hideKeyboardWhenTappedAround()
EDIT Based on comment
In theory the following code should help, but I haven't got around to test it, I've read that people couldn't get the touchBegan function to trigger but I also don't know any other way to do what you want.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
if let touch = touches.first
let position = touch.location(in: view)
if let ip = tableView.indexPathForRow(at: position)
let cell = tableView.cellForRow(at: ip)
print(cell.text)
The theory is the following
First we get the position where the tap occurred then we get the IndexPath for the row witch was taped (if exists) as we have the IndexPath we just get the cell.
In the example I gave you I print the cell text, but you can do any other operation that you want
I hope this is what you want and you can get it to work as I did not got around to test it and seems that some people are getting problems triggering the touchesBegan function
I don't think you understood the question. The keyboard dismisses before a table view cell is selected. I'm trying to have the table view tap register first. Do you know how to do this?
– jimmyruby
Aug 10 at 17:46
@jimmyruby I misunderstood your question, I think the update fits your needs. I will however leave the previous part has it can help other users
– Pedro Cavaleiro
Aug 11 at 2:26
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Will help if you post your code that handles the field and table events that are giving you trouble.
– benvc
Aug 10 at 17:56