问题描述:

I've used the first cell of tableview to be like header, for example in cellForRowAtIndexPath:

if indexPath.row == 0 {

cell.label.text = "Header"

}else {

// fill up the data

cell.label.text = array[indexPath.row]

}

And in numberOfRowsInSection I'm returning this :

return array.count

lets say I've 20 element in my array, and i reserved the first cell as header thus one of the elements will be eliminated. and if i increased the array.count + 1 , and array[indexPath.row + 1] to solve the issue, so i get array out of bounds. i just want to use first cell as header and the rest of data in the next 20 cell. why couldn't that happen !

网友答案:

I think you meant to use 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
    }
}
网友答案:

you should put a placeholder in your array for the header, then the array.count will include the header, and the placeholder can be index properly with indexPath.row so you wont get an out of bounds error

otherwise if thats not an option you will have to make an exception when indexing your array, so like

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

  return normalCell;
}
网友答案:

After get data, you should create an empty object for the header in your data.

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

网友答案:

Imho it would be easier to get the first element of your array, create your custom header view and remove it from your array so you will just have to handle normal 'uitableviewcells' with the stuff in the array and you don't need to use any conditions. There is a 'delegate' where you can setup the 'uitableviewheader' , thisshould also be the place where to put it.

网友答案:

You can do this in two types

First is

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]);
}

Second is

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";
}
相关阅读:
Top