开发者

iPhone: How to add rows in tableview after tabelview already loaded?

I have implemented "Add to Favourites" functionality for my iPhone application. It works fine except adding cells into my Favourite Table View during runtime. For example, I have given following methods.

- (void)viewWillAppear:(BOOL)animated 
{
    [super viewWillAppear:animated];

    tableView.hidden = YES;
    warningLabel.hidden = YES;

    // Load any change in favourites
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *data = [defaults objectForKey:kFavouriteItemsKey];
    self.favourites = [NSKeyedUnarchiver unarchiveObjectWithData:data];

    if([self.favourites count] > 0) 
        tableView.hidden = NO;
    else 
        warningLabel.hidden = NO;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return [self.favourites count]; // Favorites is a dictionary contains required data
}

- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
       cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [NSString stringWithFormat:@"index: %d",indexPath.row];

    return cell;
}

This code works fine and display rows correctly for the first time only! After tableview is loaded and if I add new item(s) in favorites or delete any item(s), it doesn't make any difference to my tableview! I want to display exactly what is available in Favourites dictionary. It seems CellForRowAtIndexPath doesn't get invoked when ViewAppear again. I开发者_运维知识库s there any method for TableView that I can use to achieve my requirements?


I think you've missed to call [tableView reloadData];


The very easy way is to just call [tableView reloadData] whenever you make any changes.

There is also a better (faster for large tables, and possibly animated; more elegant), but much more complicated way which I won't go into unless you decide the reloadData way isn't sufficient for you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜