有什么办法可以在UITableViewController以外的UIViewController中使用原型单元格吗?

问题描述:

我把我的tableView作为UIViewController的子视图,在storyboard中,我添加了原型单元格到这个场景。但似乎故事板中单元格的设计不起作用,似乎原型单元格仅适用于UITableViewController?有什么办法可以在UITableViewController以外的UIViewController中使用原型单元格吗?

,这里是我的故事板设计,我使用的tableView作为视图控制器的子视图,并在它(粉红色和蓝色细胞) enter image description here

,这里是我的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将只有两个空白单元格(似乎故事板中的设计不工作) enter image description here

+0

你正在收到什么错误。你可以添加一些代码吗?它应该工作,如果你有正确的设置来源和委托。 –

+0

@kapsym thx,我刚刚发布了我的故事板设计和代码,有什么不对吗? – ximmyxiao

+0

你能描述一下你期望会发生什么,并且实际发生了什么?在这种情况下,“不起作用”是什么意思? – Moshe

如果您正在使用的故事板设计,你不需要下面的线

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

取而代之的是,你需要为小区标识在故事板作为下面的图片

enter image description here

在你想检查一些东西,以确保你的表格视图是连线的,并知道在SubViewController类中寻找单元格。

  1. 确保UITableView的出口设置为可以在代码中引用的东西。除非您使用UITableViewController子类,否则不会自动连接self.tableView
  2. 确保您的表格视图具有SubViewController类,因为它是数据源和委托。您可以在代码中执行此操作,也可以通过拖入界面构建器来完成此操作。尝试将其添加到您的viewDidLoad方法中:self.tableView.dataSource = self;
  3. 您可能希望将您的单元设置为在Interface Builder的检查器面板中使用字符串标识符。然后,在cellForRowAtIndexPath:中,使用该标识符将您的单元出列,而不是按类名称注册。

顺便说一句,你还可以使用原型细胞UICollectionView但是API和故事板的设置非常相似,并且相同的步骤适用。

+0

感谢@Moshe,似乎问题在于我为原型单元调用了registerClass,当我删除这些调用时,单元格显示良好 – ximmyxiao

+0

不错,很高兴您能够正常工作。 – Moshe