MOMMH MOMMH - 1 year ago 79
Swift Question

how prevent dequeueReusableCellWithIdentifier to repeat my segment select?

I have table contains custom cells contain uisegment
The problem is when select any item in uisegment and scroll down in the table view it change the selection in uisegment in the cells down on table

almost cell 1 like 11 and 2 like 12

It related to dequeueReusableCellWithIdentifier and my question is what is the best way to solve it ?

enter image description here

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

let item = self.cells.items[indexPath.row]

if let cellHedaer: TcPationQuestionHeader = tableView.dequeueReusableCellWithIdentifier("HeaderItem") as? TcPationQuestionHeader {
cellHedaer.setCell(Results.Questions[indexPath.row/2 ])

if item as? SwiftyAccordionCells.HeaderItem != nil {
let cellItem: TcPationQuestionItem = tableView.dequeueReusableCellWithIdentifier("Item") as! TcPationQuestionItem


return cellItem

cellHedaer.selectionStyle = UITableViewCellSelectionStyle.None
return cellHedaer

Szu Szu
Answer Source

I see 2 major problems in your code:

  1. You shouldn't keep the state inside UI. Every accessing data from UI is a big mistake. You should keep selection inside model. The easiest way is to keep array var inside controller.

  2. In some cases you will call dequeueReusableCellWithIdentifier 2 times. That shouldn't happen too.

Don't forget the implementation of cellForRow is connected to numberOfRowsAtIndexPath and numberOfSections. If you want to more detailed help paste here these 2 functions.