2011-03-30 60 views
12

我使用viewDidLoad中的数组初始化表中的数据,然后将数据添加到单元中。这是我读书的一种标准方式。 这是我有:如何更新tableView中的数据?

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    //Create array and add data ("tableViewValues" is initialized in .h file) 
    tableViewValues = [[NSMutableArray alloc]init]; 
    [tableViewValues addObject:@"$280,000.00"]; 
    [tableViewValues addObject:@"$279,318.79"]; 
} 

// Customize the appearance of table view cells. 
- (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] autorelease]; 
    } 

    NSString *cellValue = [tableViewValues objectAtIndex:indexPath.row]; 

    cell.textLabel.text = cellValue; 

    return cell; 
} 

所以,当视图加载,这两个货币价值都在我的表。 现在在另一个函数中,我使用不同的货币编号填充另一个数组,具体取决于用户在文本字段中输入的内容。我将如何更新我当前的表视图,并用我的另一个数组中的值替换这些值?谁能帮我?谢谢!

回答

37

您可以拨打

[self.tableView reloadData]; 

重新加载的所有数据,但是,你需要一种方法来有你想要填充表的阵列进行编程。也许你想让你的-cellForRowAtIndexPath调用一个私有方法来有条件地选择正确的数组。

+0

我得到了重新加载数据的工作,谢谢。但我在填充数组中的值时遇到问题?你能详细说明怎么做吗? – serge2487 2011-03-30 06:08:46

+0

这取决于。获得新值后,是否需要返回初始值?什么是你的表更新值。很难说没有更多的信息。 – Jamie 2011-03-30 06:29:52

+0

我有一个textfield委托“shouldChangeCharactersInRange”,我用该方法中的数字填充数组。所以阵列不断变化。我不在乎旧的价值观。每次调用方法时,我只想获取数组值并将其放入表中。 – serge2487 2011-03-30 07:05:42

1

你需要(释放)再现同一tableViewValues数组,然后调用reloadData方法上的tableView这样的:

[self.tableView reloadData]; 

如果你表视图控制器和self.tableView指向这将工作有问题的桌子。

2

你必须从你的数组中删除所有的值,那么你必须调用表重装数据

// In the method where you will get new values 
[tableViewValues removeAllObjects]; 
[tableViewValues add:@"new values"]; 
//reload table view with new values 
[self.tableView reloadData]; 
+0

同样的问题。这增加了什么新东西?因为它基本上与已被接受的答案相同。 – 2013-05-17 06:37:42

1
在功能

,到新数组分配值后,所有你需要做的就是

[tableViewValues removeAllObjects]; 
tableViewValues = [[NSMutableArray alloc] arrayByAddingObjectsFromArray:newArray]; 
[self.tableView reloadData]; 
+0

谢谢,这就是我所追求的! – Jordan 2015-03-10 05:48:53

2

我已经有过这个问题多次,我总是犯同样的错误。

[self._tableview reloadData]作品!

问题是填充表格的地方。

我这么做是 - (无效)viewDidLoad中和表是更新相同的数据。显然没有任何反应。

在之前调用[self._tableview reloadData]的同一位置更新表视图(plist,dictionary,array,whatever)的内容。

这是关键!

做一个测试:

#pragma mark - Actions 

- (IBAction)refreshParams:(id)sender { 

    self.dictionary = nil; 

    [self._tableView reloadData]; 
} 

你可以看到,当你按下刷新按钮是如何消失的tableview内容。显然,这是一个例子。我使用字典来填充表格和一个按钮来刷新内容。

0
[self.tableView reloadData]; 

会帮助你这个。

相关问题