2011-07-07 98 views
0

我已經爲我的iPhone應用程序實現了「添加到收藏夾」功能。它運行良好,除了在運行時將單元格添加到我的收藏夾表視圖中例如,我給出了以下方法。iPhone:如何在tabelview已經加載後在tableview中添加行?

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

此代碼工作正常,僅在第一次正確顯示行!在tableview加載後,如果我在收藏夾中添加新項目或刪除任何項目,它對我的​​tableview沒有任何影響!我想要精確顯示收藏夾字典中的可用內容。看來CellForRowAtIndexPath不會在ViewAppear再次被調用。有什麼可以用來實現我的需求的TableView方法嗎?

回答

6

我想你已經錯過了來電[tableView reloadData];

+0

Yah..silly me!謝謝! – applefreak

+0

@AppleDeveloper,乾杯;-) – EmptyStack

0

非常簡單的方法是隻需撥打[tableView reloadData]每當你做任何更改。

還有一個更好的辦法(對於大型表格更快,也可能是動畫;更優雅),但更復雜的方式,除非您決定採用reloadData方式,否則我不會進入。

相關問題