Search code examples
iosswiftuitableviewalamofire

Changing button color in cell if clicked


I'm trying to create like button in tableview cell for my project. If like button clicked it must change tint color to red. I'm using Alamofire and if user liked it returns wich feed is liked and in cell:

let likerHash = data[indexPath.row]["liker_hash"] as? String
if(likerHash == ""){
   cell.likeButton.tintColor = UIColor.blackColor()
}else{
   cell.likeButton.tintColor = UIColor.redColor()
}

will set color of buttons for feeds. But if i click one button to like if it's not liked it changes color and iwhen i scroll down and come back again button color will change again to previous. (if on loading data it is not liked it will keep color when i scroll down.) I have tride to change value of liker_hash but it gives me an error: mutating method sent to immutable object. I am tying to change value like:

self.data[sender.tag]["liker_hash"] = ""

My data is from type [NSMutableDictionary](). Any idea how can i do it in swift language?


Solution

  • The main feature with using dequeueReusableCellWithIdentifier is that the cell is recreated every time you come back to it. Based on the code that you've added, I don't believe you're editing your data source when the user hits the like button to save which cell has been changed the next time the tableView reloads.

    What I'd suggest is holding all the cells in an array. Supposed you have 5 cells, create an array holding their current state:

    var cellArr = ["Black", "Black", "Black", "Black", "Black"]
    

    Then, if the user selects the like button, make sure to update this array with the right color as well. So if I select the second row, I update it like:

    var cellArr = ["Black", "Red", "Black", "Black", "Black"]
    

    And then in your cellForRowAtIndexPath function:

    if cellArr[indexPath.row] == "Black"{
        cell.likeButton.tintColor = UIColor.blackColor() }
    else {
        cell.likeButton.tintColor = UIColor.redColor()
    }