Wednesday, December 26, 2012

Adding Items to your UITableView from newest to oldest

Blog Post 14: Adding items to your UITableView with Newest on top.

I ran into a dilemma today. I have an UITableView on my app, which logs things. However, when you add a new item to list, it adds the item at the bottom. However, I found a way to fix this. After asking the question on Stack Overflow, with none of the answers working (Or easily accomplished), I took another look at my code. Then I realized, all you need to do is move an item at it's index behind the scenes. I already had a method for moving items, which can be seen from the following:

-(void)moveItemAtIndex:(int)from toIndex:(int)to
    if (from == to) {
    LEItem *p = [allItems objectAtIndex:from];
    [allItems removeObjectAtIndex:from];
    [allItems insertObject:p atIndex:to];

Alright, as is pretty clear. allItems is an array of LEItem's (A custom object for my app). Now, all I need to do is use this when I add an item, done with the following code:

-(LEItem *)createItem
    LEItem *p = [LEItem addNewItem];
    [allItems addObject:p];
    NSUInteger index = [allItems indexOfObject:p];
    [self moveItemAtIndex:index toIndex:0];
    return p;

Problem solved. New items go at the top of your list!

Note: If this helped you, then help me out. If you have a Stack Overflow account, +1 my answer. I'm Ace Legend on Stack Overflow.

Here's the link:

No comments:

Post a Comment