iOS:从现有单元格以编程方式创建表“标题”

时间:2014-09-05 20:35:24

标签: ios objective-c uitableview xcode5

我的tableOne包含名为CustomCellForTableOne(.h和.m)的自定义UITableViewCell。当用户点击tableOne中的单元格时,我希望它们转到tableTwo。到目前为止这么容易。

我希望tableOne中的单元格成为tableTwo中的表头。这样做有简单直接的方法吗?理想情况下,我想简单地从通过segue传递的数据创建一个CustomCellForTableOne,并将该单元格指定为tableTwo的标题。

  1. 我不知道如何以编程方式为表格分配标题(所以我可以试试)
  2. 会有用吗? (因为我还没有尝试过,我想我可能会要求节省一些时间)或者我必须采取一些不同的方法吗?

4 个答案:

答案 0 :(得分:1)

表的单元格和标题视图都应该可以从UIView继承。在tableTwo中实现以下内容并从中返回表视图单元实例。 -

 - (UITableViewHeaderFooterView *)headerViewForSection:(NSInteger)section

答案 1 :(得分:1)

表格视图中很难处理标题。我会在第二个表中放置一个额外的部分,仅用于已经通过的特定单元格。这可能是第二个表的第一部分,您可以将其设计为看起来像标题。

另一种方法是创建一个普通视图并将其放在第二个表的标题中(这是完全合法的)。然后,您可以通过addSubView:在该普通视图中安全地添加您的特定单元格(如果它有视图)。

答案 2 :(得分:1)

我能够实现您在第一个视图控制器中使用以下代码所要做的事情:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // create the new table view
    TestTableViewController2 *testView2 = [TestTableViewController2 new];

    // get a reference to the cell that they clicked and create a totally new cell, a 'copy' of
    // the original that we can pass to the next view
    UITableViewCell *clickedCell = [tableView cellForRowAtIndexPath:indexPath];
    UITableViewCell *clickedCellCopy = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
    clickedCellCopy.textLabel.text = clickedCell.textLabel.text;
    clickedCellCopy.detailTextLabel.text = clickedCell.detailTextLabel.text;

    // set this new cell as the header cell on the new view
    testView2.myHeaderCell = clickedCellCopy;

    // push the new view onto the stack
    [self.navigationController pushViewController:testView2 animated:YES];
}

然后将该属性添加到第二个表视图控制器:

@property (nonatomic, retain) UITableViewCell *myHeaderCell;

然后在.m的viewDidLoad:

- (void)viewDidLoad {
    [super viewDidLoad];

    // set our header cell as the table view's header
    self.tableView.tableHeaderView = self.myHeaderCell;
}

这给了我以下结果:

https://www.dropbox.com/s/t42lraue1kfolf3/cell%20demo.mov?dl=0

答案 3 :(得分:0)

您可以在xib文件中创建自定义UITableViewCell并为每个视图加载它。您将不得不在两个视图控制器中创建它。根据复杂程度,您也可以在代码中完全执行此操作。