开发者

iPad: Keeping a selected table view cell on screen

On the iPad I show a UIPopover when the user selects cells in a UITableView. The cell stays selected until the popover is dismissed.

When the user rotates the device from portrait to landscape orientation and the selected cell was on the lower part of the screen, it will disappear after the rotation and the popover ends up pointing at another (indifferent) cell.

How can I make sure that the selected cell in a UITableView stays o开发者_StackOverflown screen when rotating from portrait to landscape orientation?

Update: Combining Caleb's and kviksilver's codes, the following is a working solution:

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    CGRect activeCellRect = [self.tableView rectForRowAtIndexPath:self.indexPath];
    if ((activeCellRect.origin.y + activeCellRect.size.height) >
        (self.view.frame.origin.y + self.view.frame.size.height))
    {
        // If a row ends up off screen after a rotation, bring it back
        // on screen.
        [self.tableView scrollToRowAtIndexPath:self.indexPath
                              atScrollPosition:UITableViewScrollPositionBottom
                                      animated:YES];
    }
}

Update 2, on repositioning the UIPopover: After the scroll command it is necessary to send a reloadData message to the table view. Then the rectForRowAtIndexPath: method will correctly report the new position of the cell (otherwise it will not, as it is not updated properly after the scroll-command)!


On orientation change try checking indexPathsForVisibleRows to see if your cell is visible and then using scrollToRowAtIndexPath if not.. something like:

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
    if (![[self.tableView indexPathsForVisibleRows] containsObject:[self.tableView indexPathForSelectedRow]]) {
        [self.tableView scrollToRowAtIndexPath:[self.tableView indexPathForSelectedRow] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
}


You already know which row is selected, right? You also know when the device orientation changes, or at least you can know that, because there are UIViewController methods for that. You can get the rectangle for the selected row using UITableView's -rectForRowAtIndexPath: method, and it's easy to make sure that rectangle stays visible using UIScrollView's -scrollRectToVisible:animated: method, which UITableView inherits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜