从另一个UIViewController中的字符串更新UITableView中的数据

时间:2014-03-27 04:43:48

标签: objective-c uitableview

基本上我有两个视图控制器:主控和细节。我希望在细节控制器中输入的字符串显示在主控制器的表格中。在主控制器

我有:

  • 名为names
  • 的NSMutableArray属性
  • 委派回来的prepareForSegque方法
  • 从第二个控制器获取字符串的方法:

    - (void)detailViewControllerAdd:(DetailViewController *)detailViewController {

        [self.names addObject:detailViewController.name];
        [self dismissViewControllerAnimated:YES completion:nil];    }
    
  • 和UITableView:

    -(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath{
    
          UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
          cell.textLabel.text = self.names[indexPath.row];
          return cell;
    }
    
    -(NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) section
    {
          return self.names.count;
    }
    

在我的第二个ViewController(详细信息)中,我有一个文本字段和一个“添加”按钮。我希望将textfield文本添加到主视图控制器的表行中。

-(IBAction)addButton: (id)sender
{
     self.name = self.nameTextField.text;
     [self.delegate detailViewControllerAdd:self];
}

很抱歉,如果这令人困惑,我会尽量保持简单。我知道名字正在被添加好,因为我可以在NSLog中看到它们。我也试过查找人们的建议,但[tableView reloadData]根本不起作用,[self.tableView]甚至不存在。

非常感谢任何帮助或建议。此外,如果有帮助,则segue动作为“模态”。

2 个答案:

答案 0 :(得分:0)

请参阅this非常受欢迎的问题。显示在视图控制器之间传递数据。显然它会有所帮助。

答案 1 :(得分:0)

在cellForRow中,如果没有可重复使用的单元格,则应创建单元格。

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

      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
      if (cell == nil) {
          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
      }

      cell.textLabel.text = self.names[indexPath.row];
      return cell;
}

如果您不想查看cell == nil,则应使用iOS6以上版本的- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath