3

I am trying to set a different style for the first row of my table view.

I'm doing this by the following code:

def tableView(table_view, cellForRowAtIndexPath: index_path)
  data_row = @data[index_path.row]
  puts index_path.row
  if index_path.row == 0
    cell = table_view.dequeueReusableCellWithIdentifier(ITEM_CELL_ID) || begin
      rmq.create(ItemCell, :first_cell, reuse_identifier: ITEM_CELL_ID).get
    end
  else
    cell = table_view.dequeueReusableCellWithIdentifier(ITEM_CELL_ID) || begin
      rmq.create(ItemCell, :rest_cell, reuse_identifier: ITEM_CELL_ID).get
    end
  end
  cell.update(data_row)
  cell
end 

Question

However I get very weird behavior with this. The first row does have the custom styling....but so does the 10th and 20th row!! I don't know why that would happen. Rows 2 - 9 and 11-19 are different than row 0 and 10 and 20.

birdy
  • 9,286
  • 24
  • 107
  • 171
  • what is that `puts index_path.row` returning? – dax May 18 '14 at 18:36
  • it is returning `0, 1, 2, 3...10...15...20..` etc. I even tried puts index_path.class.to_s and that returns `Fixnum` – birdy May 18 '14 at 18:39
  • shot in the dark, but what if you try `if index_path.row/2 == 0` - might work, might not, but if it doesn't then you'll know for sure that it's not the number comparison causing it – dax May 18 '14 at 18:49
  • that doesn't work either. I think the issue with with iOS painting only a few rows to begin with and then repainting them on the screen on scroll or something. so weird – birdy May 18 '14 at 18:58

2 Answers2

0

not sure how your method is being called, so maybe this isn't possible...but, I imagine this is being called from a collection (or that there is a collection involved somewhere along the stack). could you do something like this:

#wherever you're calling this from 
index_paths.each_with_index do |path, i| #add an 'index path'
  tableView(table_view,  cellForRowAtIndexPath: path, i)
  ...
end

#updated original method
def tableView(table_view, cellForRowAtIndexPath: index_path, path_index) #add path index
  data_row = @data[index_path.row]
  puts index_path.row
  if path_index == 0 #add path index
    cell = table_view.dequeueReusableCellWithIdentifier(ITEM_CELL_ID) || begin
      rmq.create(ItemCell, :first_cell, reuse_identifier: ITEM_CELL_ID).get
    end
  else
    cell = table_view.dequeueReusableCellWithIdentifier(ITEM_CELL_ID) || begin
      rmq.create(ItemCell, :rest_cell, reuse_identifier: ITEM_CELL_ID).get
    end
  end
  cell.update(data_row)
  cell
end 
dax
  • 10,779
  • 8
  • 51
  • 86
0

You need to use different ITEM_CELL_ID (reuseIdentifiers) for each cell type. So the :first_cell styled cell should have a different reuseIdentifier constant than the :rest_cell styled cells. That should fix your issue since what you're seeing is that first cell's memory being reused over and over again as the table scrolls.

markrickert
  • 648
  • 1
  • 5
  • 10