Bhrigesh
Bhrigesh

Reputation: 871

Table View Scrolling Issue with content offset

I am trying to scroll my table view to show my last cell when keyboard is active. This is what i am doing in tableView:cellForRowAtIndexPath:...

if (keyboard) {

    CGFloat calculatedPosY = 70 * ([Array count]-1);
    MyTable.contentOffset = CGPointMake(0.0, calculatedPosY);

}

its working correctly for first time but for second time when its reloading table its not scrolling. For third time its again scrolling and showing last cell of table. Alternatively the code is working and the log gives the same content offset (0,280).

Please tell were I am doing wrong. Thanks in advance.

Upvotes: 1

Views: 1674

Answers (3)

Karl Monaghan
Karl Monaghan

Reputation: 910

You need to do two things - 1) make sure the table view fits on the visible part of the screen not covered by the keyboard and 2) scroll the table to the last row.

To resize the view, I'd register to detect the keyboard appearing:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector (keyBoardWillShow:)
                                             name: UIKeyboardWillShowNotification object: nil];

The keyBoardWillShow: method would be called when the keyboard appears and you can resize the tableview:

- (void)keyBoardWillShow:(NSNotification *)aNotification
{
    NSValue *value = [[aNotification userInfo] objectForKey: UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];

    CGFrame tableFrame = self.tableView.frame;
    tableFrame.height -= keyboardRect.size.height 
    self.tableView.frame = tableFrame;
}

Lastly, scroll to the last cell (you could do this in keyBoardWillShow: if you like):

[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:lastRowIndex inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];

Upvotes: 1

Adithya
Adithya

Reputation: 4705

I would suggest you use – scrollToRowAtIndexPath:atScrollPosition:animated:. Its a method in the UITableView.

Upvotes: 0

pbibergal
pbibergal

Reputation: 2921

Don't do it in tableView:cellForRowAtIndexPath:.. this method iterates through all array elements and creates cell. It means this calculation runs array[N] times.

Instead run it once after [self.tableView reloadData];

Or try this:

NSInteger *cells_count // You can have it from - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section.

//Run this after [tableView reloadData]
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:cells_count-1 inSection:0];
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated: NO];

Upvotes: 0

Related Questions