Maulik Maulik - 1 year ago 131
Objective-C Question

How to scroll UITableView to specific position

How can I scroll the table's cell to specific position ? I have a table which shows 3 rows (according to height). what I want is if I click on 1st row than according to table's height the 1st row should scroll and get new position (center) and same for other rows. I tried contenOffset but did not work..


In short some thing like data picker when we select any row in picker the row scrolls to the center.


Answer Source

finally I found... it will work nice when table displays only 3 rows... if rows are more change should be accordingly...

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    return 1;

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView 
    return 30;

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault    
                                       reuseIdentifier:CellIdentifier] autorelease];

    // Configure the cell.
    cell.textLabel.text =[NSString stringWithFormat:@"Hello roe no. %d",[indexPath row]];

    return cell;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    UITableViewCell * theCell = (UITableViewCell *)[tableView     

    CGPoint tableViewCenter = [tableView contentOffset];
    tableViewCenter.y += myTable.frame.size.height/2;

    [tableView setContentOffset:CGPointMake(0, animated:YES];
    [tableView reloadData];