除了 UITableViewController 之外,还有什么方法可以在 UIViewController 中使用原型单元吗?

Is there any way to use prototype cells in UIViewController other than UITableViewController?

我将我的 tableView 作为 UIViewController 的子视图,并且在故事板中,我将原型单元添加到这个场景。但似乎故事板中单元格的设计不起作用,似乎原型单元格仅适用于 UITableViewController?

这是我的故事板设计,我使用 tableView 作为 ViewController 的子视图,并在其中添加两个原型单元格(粉色和蓝色单元格)

这是我的 tableView 代码:

@implementation SubViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"TableViewCell"];
    [self.tableView registerClass:[ATableViewCell class] forCellReuseIdentifier:@"ATableViewCell"];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

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

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        TableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell" forIndexPath:indexPath];
        return cell;
    }
    else
    {
        ATableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"ATableViewCell" forIndexPath:indexPath];
        return cell;
    }
}

当我 运行 我的代码时,我希望会有一个蓝色和粉红色的单元格,但实际上,tableView 只会有两个空白单元格(似乎情节提要中的设计不起作用)

如果您使用 Storyboard 进行设计,则不需要以下几行

[self.tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"TableViewCell"];
[self.tableView registerClass:[ATableViewCell class] forCellReuseIdentifier:@"ATableViewCell"];

相反,您需要为情节提要中的单元格设置标识符,如下图所示

您想检查一些事情以确保您的 table 视图已连接并且知道在 SubViewController class.

中查找单元格
  1. 确保 UITableView 的出口设置为您可以在代码中引用的内容。 self.tableView 不会自动连接,除非您使用 UITableViewController subclass。
  2. 确保您的 table 视图已连接 SubViewController class 作为数据源和委托。您可以在代码中执行此操作,或通过拖入界面构建器来执行此操作。尝试将此添加到您的 viewDidLoad 方法中:self.tableView.dataSource = self;
  3. 您可能希望将单元格设置为在 Interface Builder 的检查面板中使用字符串标识符。然后,在 cellForRowAtIndexPath: 中,使用该标识符使您的单元格出队, 而不是 通过 class 名称注册。

顺便说一句,您也可以将原型单元与 UICollectionView 一起使用,但 API 和情节提要设置非常相似,并且适用相同的步骤。