使用TableView第一个单元格作为标题和问题

时间:2015-11-02 07:11:16

标签: ios objective-c arrays uitableview

我已经将tableview的第一个单元格用作标题,例如在cellForRowAtIndexPath中:

if indexPath.row == 0 {
cell.label.text = "Header"

}else {

// fill up the data 
cell.label.text = array[indexPath.row]
}

numberOfRowsInSection我回来了:

return array.count

假设我的数组中有20个元素,并且我将第一个单元格保留为标题,因此其中一个元素将被删除。如果我增加了array.count + 1array[indexPath.row + 1]以解决问题,那么我就会让阵列超出范围。我只想在下一个20个单元格中使用第一个单元格作为标题和其余数据。为什么不会发生这种情况!

5 个答案:

答案 0 :(得分:2)

我认为您打算使用array[indexPath.row - 1]

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if indexPath.row > 0 {
        let entry = array[indexPath.row - 1]
    } else {
        //Configure the placeholder cell
    }
}

答案 1 :(得分:1)

你应该在数组中为占位符添加一个占位符,然后array.count将包含标题,占位符可以使用indexPath.row正确索引,这样你就不会出现越界错误

否则,如果那不是一个选项,则在索引数组时必须做出异常,所以就像

一样
//psuedo code
if (indexPath.row == 0) {
  return headerCell;
}
else {
  data = array[indexPath.row-1];

  return normalCell;
}

答案 2 :(得分:1)

获取数据后,您应该为数据中的标题创建一个空对象。

[array insertObject:@"header" atIndex:0];

答案 3 :(得分:0)

Imho可以更轻松地获取阵列的第一个元素,创建自定义标题视图并将其从阵列中删除,这样您就必须处理正常的“uitableviewcells”。使用数组中的内容,您不需要使用任何条件。有一个代表'你可以在哪里设置' uitableviewheader' ,这也应该是放置它的地方。

答案 4 :(得分:0)

您可以使用两种类型执行此操作

首先是

if (indexPath.row == 0 )
{
   cell.textLabel.text = @"Header";
} 
else {
   cell.textLabel.text = array[indexPath.row - 1];
   NSLog(@"The cell index is - %@",array[indexPath.row - 1]);
}

第二是

if (indexPath.row > 0 )
{
    cell.textLabel.text = array[indexPath.row - 1];
    NSLog(@"The cell index is - %@",array[indexPath.row - 1]);
} 
else 
{
  cell.textLabel.text = @"Header";
}