如何使用不同的内容uitableviewcell

时间:2013-12-30 13:28:23

标签: ios objective-c uitableview

我正在使用UITableView群组类型,我正在UITableViewCell添加不同的内容 每个indexPath.section我正在检查UITableViewCell委托方法

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {

        cellIdentifier = (indexPath.row % 2 == 0 ? @"EvenCell" : @"OddCell");
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
        if (cell == nil) 
    {
            cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
                              reuseIdentifier:cellIdentifier];
            if (indexPath.section == 0) 
            {
                 // adding image

                // called
            }
     else if (indexPath.section == 1) 
            {
               // adding lable
                called
            }
 else if (indexPath.section == 2) 
            {

                // adding panorma gps
                called
            }
 else if (indexPath.section == 3) 
            {
               not  called  // this section problem
            }
else if (indexPath.section == 4) 
            {
               not  called  // this section problem
            }
        }
return cell;
   }

我已经给出了第5节的数量,但它只调用indexPath.section 0,1和2。

3 个答案:

答案 0 :(得分:0)

确保你从这里返回5

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

答案 1 :(得分:0)

问题在于,您只有两种类型的cellIdentifier值(即您重复使用的两种类型的单元格),但您似乎有五种不同的布局。问题是只有在找不到重用的单元格时才会调用布局。因此,当您进入第3部分时,dequeueReusableCellWithIdentifier可能会成功并重新使用已滚出屏幕的单元格,因此您的if (cell == nil)块内的代码根本不会被调用3和4。

您可以通过拥有更多细胞类型来解决这个问题,这些细胞类型对于区段编号也是唯一的,例如:

NSString *cellType = (indexPath.row % 2 == 0 ? @"EvenCell" : @"OddCell");
NSString *cellIdentifier = [NSString stringWithFormat:@"%@-%d", cellType, indexPath.section];

你还没有分享偶数/奇数逻辑的用途,所以我不完全确定需要什么。假设它是像backgroundColor这样简单的东西,那么我可能倾向于完全从cellIdentifier中删除偶数/奇数(并将设置背景颜色移到if (cell==nil)块之外),并且只是使用节编号的节号:

NSString *cellIdentifier = [NSString stringWithFormat:@"MyCellSection-%d", indexPath.section];

我们需要更好地了解各种单元格的不同之处(通用程度是多少),以便对格式化的最佳方式提出具体建议。但关键问题是您的cellIdentifier选项必须与if (cell == nil)块中的内容相对应。

答案 2 :(得分:0)

您可以按如下方式调用方法的数量?

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 5;
}

尝试在if(cell == nil)之后调用您的方法:

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
                                  reuseIdentifier:cellIdentifier];
}
if (indexPath.section == 0) {
    // adding image

    // called
}
else if (indexPath.section == 1) {
    // adding lable
    called
}
else if (indexPath.section == 2) {

    // adding panorma gps
    called
}
else if (indexPath.section == 3) {
    not  called  // this section problem
}
else if (indexPath.section == 4) {
    not  called  // this section problem
}