Friday, June 7, 2013

UITableView rectForSection example in Objective C (iOS).


UITableView rectForSection

Returns the drawing area for a specified section of the receiver.

- (CGRect)rectForSection:(NSInteger)section

Parameters
section
An index number identifying a section of the table view. Plain-style table views always have a section index of zero.

Return Value of [UITableView rectForSection]
A rectangle defining the area in which the table view draws the section.

UITableView rectForSection example.
CGRect sectionRect = [tableView rectForSection:indexOfSectionToScrollTo];
[tableView scrollRectToVisible:sectionRect animated:YES];

The code above will scroll the tableview so the desired section is visible but not necessarily at the top or bottom of the visible area. If you want to scroll so the section is at the top do this:

CGRect sectionRect = [tableView rectForSection:indexOfSectionToScrollTo];
sectionRect.size.height = tableView.frame.size.height;
[tableView scrollRectToVisible:sectionRect animated:YES];

Modify sectionRect as desired to scroll the desired section to the bottom or middle of the visible area.


Example of [UITableView rectForSection].
- (CGSize)contentSizeForViewInPopover {
    // Currently no way to obtain the width dynamically before viewWillAppear.
    CGFloat width = 200.0;
    CGRect rect = [self.tableView rectForSection:[self.tableView numberOfSections] - 1];
    CGFloat height = CGRectGetMaxY(rect);
    return (CGSize){width, height};
}

UITableView rectForSection example.
-(void) reloadViewHeight
{
    float currentTotal = 0;

    //Need to total each section
    for (int i = 0; i < [self.tableView numberOfSections]; i++)
    {
        CGRect sectionRect = [self.tableView rectForSection:i];
        currentTotal += sectionRect.size.height;
    }

    //Set the contentSizeForViewInPopover
    self.contentSizeForViewInPopover = CGSizeMake(self.tableView.frame.size.width, currentTotal);
}

End of UITableView rectForSection example article.