Krishna
Krishna

Reputation: 378

How to make specific UITableViewCell to be visible on screen while having more rows in UITableView

I am having 20 rows in a table view, and I have designed (or say resized) UITableView in half of the screen (Using IB) and in half screen I am showing the stuff related to particular UITableViewCell. Which cell's details are going to be shown in the half screen is decided runtime. I want the cell being visible while loading the view for say second last cell.

How can I achieve this?

Upvotes: 10

Views: 10116

Answers (6)

Use like this,

let indexPath = IndexPath(row:row, section:section)
self.tableView.scrollToRow(at:indexPath, at:.top, animated:true)

Upvotes: 0

Hrishikesh Devhare
Hrishikesh Devhare

Reputation: 934

Swift 5 version of Nico teWinkel's answer making use of UITableview's scroll rect to visible method.

let indexPath = IndexPath(row: 0, section: 0)
let cellRect = myTableView.rectForRow(at: indexPath)
myTableView.scrollRectToVisible(cellRect, animated: true)

Upvotes: 0

mauriii
mauriii

Reputation: 497

Swift 4 version of Nico teWinkel's answer, which worked best for me:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.scrollToRow(at: indexPath, at: .middle, animated: true) //scrolls cell to middle of screen
}

Upvotes: 3

Nico teWinkel
Nico teWinkel

Reputation: 880

I found the easiest way to ensure that a whole cell is visible is to ask the tableview to make sure that the rect for the cell is visible:

[tableView scrollRectToVisible:[tableView rectForRowAtIndexPath:indexPath] animated:YES];

An easy way to test it is just to put that into -(void)tableView:didSelectRowAtIndexPath: - tapping any cell will then scroll it into place if it's partially hidden.

Upvotes: 20

lawicko
lawicko

Reputation: 7344

Try scrollToRowAtIndexPath:atScrollPosition:animated::

NSUInteger indexArray[] = {1,15};
NSIndexPath *indexPath = [NSIndexPath indexPathWithIndexes:indexArr length:2];
[yourTableView scrollToRowAtIndexPath:indexPath atScrollPosition: UITableViewScrollPositionTop animated:YES];

Upvotes: 8

user971401
user971401

Reputation:

UITableView class offers :

-(void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath
             atScrollPosition:(UITableViewScrollPosition)scrollPosition
                     animated:(BOOL)animated;

which seems to be what you are looking for.

The NSIndexPath object can be built using :

+(NSIndexPath *)indexPathForRow:(NSInteger)row inSection:(NSInteger)section;

Upvotes: 13

Related Questions