如何将 UITableView 滚动到特定位置

如何将 UITableView 滚动到特定位置

问题描述:

如何将表格的单元格滚动到特定位置?我有一个显示 3 行(根据高度)的表格.我想要的是,如果我点击第一行而不是根据表格的高度,第一行应该滚动并获得新位置(中心),其他行也是如此.我试过 contenOffset 但没有用..

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.

谢谢..

最后我发现...当表格只显示 3 行时它会很好用...如果行数更多,应该相应地改变...

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 
 numberOfRowsInSection:(NSInteger)section
{  
    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     
                                              cellForRowAtIndexPath:indexPath];

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

    [tableView setContentOffset:CGPointMake(0,theCell.center.y-65) animated:YES];
    [tableView reloadData]; 
 }