Nahouto Nahouto - 3 months ago 16
Swift Question

becomeFirstResponder and estimatedRowHeight incompatibility

I have an

UITableView
containing
UITableViewCell
containing an
UITextView
.

I wanted two things :


  1. user can enter text in the
    UITextView
    and its dimension grows according to it.

  2. when user click on add button, the
    textView
    becomes first responder.



1.The first aim has been implemented as :

self.tableView.estimatedRowHeight = 44
self.tableView.rowHeight = UITableViewAutomaticDimension

func textViewDidChange(textView: UITextView) {
tableView.beginUpdates()
tableView.endUpdates()
}


and it works well

2.For the second thing, I simply wrote :

@IBAction func addButton(sender: AnyObject) {
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyCell
cell.cellTextView.resignFirstResponder()
cell.cellTextView.becomeFirstResponder()
}


and it does not work... :-(

What is even more bizarre, is that if I delete the first block of instructions above (in particular the
estimatedRowHeight
instruction), the
becomeFirstResponder
works well.

Do you have any clue to perform both functionalities ?
Thanks !

Answer

You need to use cellForRowAtIndexPath method for get cell:

@IBAction func addButton(sender: AnyObject) {
    let indexPath = NSIndexPath(forRow: 0, inSection: 0)
    tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: false) // add this line if you wish to scroll for input
    if let cell = tableView.cellForRowAtIndexPath(indexPath) as? MyCell {
        view.endEditing(true)
        cell.cellTextView.becomeFirstResponder()
    }
}
Comments