我正在尝试将信息显示到具有 2 个动态单元格的分组 UITableView
中。每个分组的 UITableView
需要被调用 10 次成为一个 View ;每个分组的 UITableView
在其 2 个单元格中显示不同的信息。
现在我正在尝试显示存储在 posts
中的数据库中的所有数据。但是,当我运行这个版本时,应用程序崩溃了。如果我将 numberOfSectionsInTableView:
中的 return [self.posts count]
更改为返回 1
,我只能加载一个部分,如预期的那样.
我的问题是如何显示 10 个分组的表格部分,每个部分都有不同的信息?
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
// Return the number of sections.
return [self.posts count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger returnValue = 2;
switch (section) {
case 0:
{
returnValue = 2;
break;
}
default:
break;
}
return returnValue;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier1 = @"Cell";
UITableViewCell *cell;
if (indexPath.section==0)
{
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1];
}
if (indexPath.row==0)
{
cell.textLabel.text = [[self.posts objectAtIndex:indexPath.row] objectForKey:@"name"];
}
if (indexPath.row==1)
{
cell.textLabel.text = [[self.posts objectAtIndex:indexPath.row] objectForKey:@"message"];
}
}
return cell;
}
最佳答案
您在 section = 0 时创建单元格。您应该每次都创建单元格。您不能从 cellForRowAtIndexPath
方法返回 nil。
按以下方式修改您的实现:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier1 = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1];
}
if (indexPath.section==0)
{
if (indexPath.row==0)
{
cell.textLabel.text = [[self.posts objectAtIndex:indexPath.row] objectForKey:@"name"];
}
//Rest of the code..
}
else if(indexPath.section ==1)
{
//Do the work with section 1.
}
//do the work for other sections...
return cell;
}
关于iphone - 动态加载分组 TableView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16183090/