How to make a specific UITableViewCell visible on the screen by having more rows in a UITableView

I have 20 rows in a table view, and I designed (or say resized) a UITableView in half the screen (using IB), and in the half-screen I show material related to a specific UITableViewCell. What cell information will be displayed on a half-screen is determined by the execution time. I want the cell to be visible when loading the view for the second cell.

How can I achieve this?

+8
source share
5 answers

UITableView offers:

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

which seems to be what you are looking for.

NSIndexPath object can be created using:

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

I found the easiest way to make sure the whole cell is visible is to ask tableview to make sure the rectangle for the cell is visible:

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

An easy way to check this is simply to put it in -(void)tableView:didSelectRowAtIndexPath: - clicking on any cell will scroll it in place if it is partially hidden.

+18
source

Try scrollToRowAtIndexPath: atScrollPosition: animated ::

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

Swift 4 version of Nico teWinkel answer that 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 } 
+2
source

Swift 5 version of Nico teWinkel's answer using UITableview scroll directly to the visible method.

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

All Articles