开发者

Shopping list, moving row to the top when selected

I am devleoping a shopping list with all the unbought items to be on the top of the UITable and all the bought items to be on the bottom. The items are read from sqlite DB When the user first clicks on a shopping list item, it means the user has bought the item. Hence i change the label to grey color and move the cell to the bottom,correspondingly in the data source as well. (i have done this by deleting the item and inserting)

However when the user clicks on it again (meaning they need to buy this again), i want the cell to move to the top. How do i do that? How do i update the datasource ?

Here is my code

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
Item *item=[[appDelegate.slist objectAtIndex:indexPath.row]retain];
NSUInteger index=indexPath.row;
NSUInteger lastindex=appDelegate.slist.count-1;

//get the cell
UITableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];

if (item.iNeed==1) {
    cell.textLabel.textColor=[UIColor lightGrayColor];
    if (index!=lastindex) {
        [appDelegate deleteSLItem:item]; //delete from DB
        item.iNeed=0;
        [appDelegate insertSLItem:item]; //insert again

    //for animation
        [tableView beginUpdates];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[开发者_如何转开发NSIndexPath indexPathForRow:lastindex inSection:0]] withRowAnimation:UITableViewRowAnimationLeft];
        [tableView endUpdates]; 
    }
}else if (item.iNeed==0) {
    item.iNeed=1;
    cell.textLabel.textColor=[UIColor blackColor];
/*
i want to know what am i supposed to do here to move the cell to the top and
correspondingly in the data source as well
*/
    [appDelegate updateSLItem:item];
}
[item release];
}


You shouldn't delete and add the item. Add a bool attribute "bought" to the model. When displaying the cells make sure to sort your array starting with the ones with bought = YES;

When you click a cell change the bought=!bought Do reloadData on the table

EDIT: if you want to have the bought ones in the correct order, instead of a bool make "bought" an int and store it's order index

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜