iphone - 动态加载分组 TableView

标签 iphone ios objective-c uitableview grouped-table

我正在尝试将信息显示到具有 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/

相关文章:

iphone - 在不同的数组中添加不同部分的选定单元格,UICollectionView

ios - 文本字段边框不仅仅出现在 iPad2 中,在 iPad Air 或可调整大小的 iPad 中也出现了

android - 如何让 PWA 应用程序访问其他 native 应用程序?

iOS 13 : Space grouping separator changed

iphone - didSelectRowAtIndexPath 上的变量清空或删除

iphone - 无法更新 iPhone 应用程序

ios - 如何在 Firebase 中查询嵌套元素?

iphone - 为什么 Reachability 示例应用程序会在此处停止?

ios - UIView 的 snapshotView 在没有任何内容的上下文中渲染/绘制

iphone - Xcode 4 - 我的应用程序已安装但从未在设备上运行