Reputation: 688
My Project:
I have an UITableView
in My project. Each and every UITableViewCell
have one UITextView
as a subview. When user tap on 'Add' button, I need to add one more UITableViewCell
with UITextView
to UITableView
and I have to set focus into the added UITextView
.
What I've Tried:
Once user tap on add button, I will update the numberOfRowsInSection
of UITableView
and subsequently I'll call [UITableView reloadData]
to invoke [UITableView cellForRowAtIndexPath]
. Here, I'll append the UITextView
as subview of UITableViewCell
.It Works fine until this point.
My problem:
I need to set focus into the UITextView
Once after the [UITableView cellForRowAtIndexPath]
get called. When I called the set focus method for UITextView
after [UITableView reloadData]
, It is not working. I want to know, Is there any callback method for [UITableView cellForRowAtIndexPath]
?
Thanks for your answers.
Upvotes: 0
Views: 274
Reputation: 5182
Try this,
In Add button action
//Assuming only 1 section, if you have more section find sections by `numberOfSections` method
NSInteger totalRows = [self.tableView numberOfRowsInSection:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:totalRows inSection:0];
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
[tableView endUpdates];
//If you have custom cell
CustomCell *cell = (CustomCell *)[self.tableView cellForRowAtIndexPath:indexPath];
[cell.textView becomeFirstResponder];
//If you are not using custom cell, then set tag to textView and
//UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//UITextView *textView = (UITextView *)[cell viewWithTag:kTextViewTag];
//[textView becomeFirstResponder];
Upvotes: 1
Reputation: 18508
after you have called your reloadData
method you can do something like this:
To get a reference to the last row in the last section…
// First figure out how many sections there are
NSInteger lastSectionIndex = [self.myTableView numberOfSections] - 1;
// Then grab the number of rows in the last section
NSInteger lastRowIndex = [self.myTableView numberOfRowsInSection:lastSectionIndex] - 1;
// Now just construct the index path
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
//Grab a reference of your cell from the last row
MyCustomCell *myCC = [self.myTableView cellForRowAtIndexPath:pathToLastRow];
//Use this cell reference to set focus to your UITextView
[myCC.myTextView setFirstResponder:YES];
Upvotes: 0