stackr
stackr

Reputation: 2742

Making a UITableView scroll like a UIPickerView

I have a UITableView on a UIViewController. And this table has "say" 5 visible categories to choose from. But in the Array that holds the content i have "say" 10 categories. What i've created now is a normal scrolling table that goes from category 1 on index 0 to category 10 on index 9. But what i'd rather have is category 1 also after category 10 and the other way around.

So basically an endless loop of a static Array.

I've tryed this with the scrollViewDidScroll: method, but when i do that it doesn't scroll like you would expect a UITableView to scroll. It RACES to a random spot and moving 1 or two categories is impossible.

Here is a sample of my code. Hope somebody can help.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == categoryView){
        if (categoryView.contentOffset.y > 0.0) {
            loopcounter++;
            NSLog(@"ScrollView Scrolled DOWN");
            [categorytablecontent insertObject:[categorytablecontent objectAtIndex:0] atIndex:[categorytablecontent count]-1];
            [categorytablecontent removeObjectAtIndex:0];
            [categoryView reloadData];
        }
        if (categoryView.contentOffset.y < 0.0) {
            loopcounter = [categorytablecontent count];
            NSLog(@"ScrollView Scrolled UP");
            [categorytablecontent insertObject:[categorytablecontent objectAtIndex:[categorytablecontent count]-1] atIndex:0];
            [categorytablecontent removeObjectAtIndex:[categorytablecontent count]-1];
            [categoryView reloadData];
        }

        a = categoryView.visibleCells;

        for (UITableViewCell *cell in a){
            NSLog(@"Current Visible cell: %@", cell.textLabel.text);
        }
        NSLog(@"Current offset: %@", categoryView.contentOffset.y);
    }
}

Upvotes: 1

Views: 1394

Answers (1)

joshOfAllTrades
joshOfAllTrades

Reputation: 1982

There is more then one good way to do this. Does your controller implement the UITableViewDataSource Protocol? If so, the easiest thing would probably be to just return the modulo of your dataset size in cellForRowAtIndexPath.

Something like:

-(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];
    }

    // Use appropriate fields for your categorytablecontent object here...
    cell.textLabel.text = [categorytablecontent objectAtIndex:(indexPath.row % [categorytablecontent count])];

    return cell;
}

This should result in a nice smooth infinite scroll that loops through your static (or dynamic) content.

Upvotes: 2

Related Questions