I created a custom UITableViewCell
, and a UITextView
was put inside this prototype cell. When I click on this textView, keyboard can bounce automatically. However, if I want to hide the keyboard, I will have to click Return
key. It isn't quite convenient.
Here's the question.
How can I resign the textView's firstResponder
for hiding the keyboard when I scroll the tableview.
cellForRowAtIndex
method is below.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if(indexPath.section == 0){
cell = self.tableView.dequeueReusableCellWithIdentifier("InputCell")!
let textView = cell.viewWithTag(102) as! UITextView
textView.editable = true
textView.keyboardType = UIKeyboardType.Default
textView.delegate = self
textView.targetForAction(#selector(FeedBackViewController.getTextViewInsideCell(_:)), withSender: textView)
}
if(indexPath.section == 1){
cell = self.tableView.dequeueReusableCellWithIdentifier("ConfirmButtonCell")!
let label = cell.textLabel
label?.text = "send"
label?.textAlignment = NSTextAlignment.Center
label?.textColor = UIColor.redColor()
}
return cell
}
Here are some methods I have implemented.
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool{
if(text == "\n"){
textView.resignFirstResponder()
return false
}
return true
}
And I have no idea how to implement this method.
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
}
You can try implement this on viewDidLoad
, it will auto dismiss keyboard when tableview start dragging:
tableView.keyboardDismissMode = .Interactive
or .OnDrag
UITableView
inherited from UIScrollView
that conforms to UIScrollViewDelegateProtocol
. Try to override scrollViewDidScroll
function from it and resign first responder from textview.
Be sure to assign tableView's delegate to your view controller, and then add the following code
func scrollViewDidScroll(scrollView: UIScrollView) {
yourTextView.resignFirstResponder()
}
As per docs scrollViewDidScroll
Tells the delegate when the user scrolls the content view within the receiver.
Update
Another approach to resign first responder is to set endEditing
to true
for your view:
Causes the view (or one of its embedded text fields) to resign the first responder status.
func scrollViewDidScroll(scrollView: UIScrollView) {
self.view.endEditing(true)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With