Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView inside a UITableViewCell, how to resign textview's firstResponder when tableView scrolls?

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) {

}
like image 769
Mango Ryan Avatar asked Aug 22 '16 11:08

Mango Ryan


2 Answers

You can try implement this on viewDidLoad, it will auto dismiss keyboard when tableview start dragging:

tableView.keyboardDismissMode = .Interactive or .OnDrag

like image 171
Tj3n Avatar answered Oct 21 '22 23:10

Tj3n


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)
} 
like image 30
Evgeny Karkan Avatar answered Oct 21 '22 22:10

Evgeny Karkan