有什么办法可以在UITableViewController以外的UIViewController中使用原型单元格吗?
问题描述:
我把我的tableView作为UIViewController的子视图,在storyboard中,我添加了原型单元格到这个场景。但似乎故事板中单元格的设计不起作用,似乎原型单元格仅适用于UITableViewController?有什么办法可以在UITableViewController以外的UIViewController中使用原型单元格吗?
,这里是我的故事板设计,我使用的tableView作为视图控制器的子视图,并在它(粉红色和蓝色细胞)
,这里是我的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将只有两个空白单元格(似乎故事板中的设计不工作)
答
在你想检查一些东西,以确保你的表格视图是连线的,并知道在SubViewController
类中寻找单元格。
- 确保UITableView的出口设置为可以在代码中引用的东西。除非您使用UITableViewController子类,否则不会自动连接
self.tableView
。 - 确保您的表格视图具有
SubViewController
类,因为它是数据源和委托。您可以在代码中执行此操作,也可以通过拖入界面构建器来完成此操作。尝试将其添加到您的viewDidLoad
方法中:self.tableView.dataSource = self;
- 您可能希望将您的单元设置为在Interface Builder的检查器面板中使用字符串标识符。然后,在
cellForRowAtIndexPath:
中,使用该标识符将您的单元出列,而不是按类名称注册。
顺便说一句,你还可以使用原型细胞UICollectionView但是API和故事板的设置非常相似,并且相同的步骤适用。
你正在收到什么错误。你可以添加一些代码吗?它应该工作,如果你有正确的设置来源和委托。 –
@kapsym thx,我刚刚发布了我的故事板设计和代码,有什么不对吗? – ximmyxiao
你能描述一下你期望会发生什么,并且实际发生了什么?在这种情况下,“不起作用”是什么意思? – Moshe