Search code examples
iosswiftuitableviewuibuttonuicontrolstate

UITableViewCell does not hold the state of custom button


I have read through similar questions but I haven't been able to solve it. I have a tableview which has a custom cell with a button to add and remove a class. I created a custom delegate to save and remove the class, and to change the state of the button. Changing the state of the button works fine, but when I'm scrolling the buttons don't hold the state (I'm guessing is because I'm dequeuing the cells)

in my cell for row at index path i tried checking to change the state of the button:

let isInSchedule = self.isClassScheduled(classAttend, from: self.classesInSchedule!)
    if isInSchedule == true {
        cell.addRemoveButton.selected = true

    } else {
        cell.addRemoveButton.selected = false
    }

and here is my delegate method where I save or remove the class

 func indexOfClassSelectedWithButton(index: NSIndexPath, tableView:UITableView, and button: AddRemoveClass) {
    if let currentlySavedClasses = ManagedObjectsController.sharedInstance.getAllScheduledClasses() as? [ClassScheduled] {
    let classSelected = self.classes[index.section]
    switch button.selected {
    case true:
            for classItem in currentlySavedClasses {
                if classSelected.presentation?.title == classItem.presentation?.valueForKey("title") as? String {
                    ManagedObjectsController.sharedInstance.deleteScheduledClass(classItem)
                    button.selected = false
                }
            }
        break
    default:
        if let classSelectedBreakout = classSelected.breakout?.valueForKey("breakoutID") as? String {
            let canSave = self.isBreakoutAvailable(classSelectedBreakout, allClasses: currentlySavedClasses)
            if canSave {
                ManagedObjectsController.sharedInstance.createScheduledClass(from: classSelected)
                button.selected = true
            } else {
                NSNotificationCenter.defaultCenter().postNotificationName(timeConlictNotication, object: nil)
            }
        }
      break
    }
    }
}

it changes the button state but when I start scrolling up or down the buttons don't hold the state (I'm aware is probably because I'm revising my cell so it is taking any cell that it is available. Any help is greatly appreciated.

Also, I have my cell within my view controller in story board. Why is is that if i do cell = PresentationCell() all of the views in my cell are nil? Im just trying to not reuse the cell as my last solution.


Solution

  • The solution came from @Michael " any state you need must be maintained outside of the cell" since the tableView reuses the cells that are already created I had to add a property to the class Im populating the tableview with (I used a bool but it can be anything) and based on that property I set the state of the button in the method cellForRowAtIndexPath.