Jack.Right Jack.Right - 6 months ago 38
Swift Question

Unable to change the image of UItableviewcell button

i am working on app in which i am using checkbox. so i am using uitableview and in every cell there is a checkbox button so when user tape on that cell or button. image of that button must be change to selected. but when i tape on any cell or button image is not getting change.

here is my code which i tried while click on cell

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

let cell : categoryCell = tableView.dequeueReusableCellWithIdentifier("categoryCell") as! categoryCell
let dic : NSDictionary = categoryitem.objectAtIndex(indexPath.row) as! NSDictionary
cell.category_name.text = dic.valueForKey("category_name") as? String


return cell

}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categoryitem.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

let cell : categoryCell = tableView.dequeueReusableCellWithIdentifier("categoryCell") as! categoryCell

cell.category_button.setImage(UIImage(named: "check_checkbox"), forState: UIControlState.Normal)
let dic : NSDictionary = categoryitem.objectAtIndex(indexPath.row) as! NSDictionary
print(dic.valueForKey("category_id") as! String)
}

Answer

Change your code in didSelectRowAtIndexPath as

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let cell : categoryCell = tableView.cellForRowAtIndexPath(indexPath) as! categoryCell

    cell.category_button.setImage(UIImage(named: "check_checkbox"), forState: UIControlState.Normal)
    let dic : NSDictionary = categoryitem.objectAtIndex(indexPath.row) as! NSDictionary
    print(dic.valueForKey("category_id") as! String)
}

Mistake you did

let cell : categoryCell = tableView.dequeueReusableCellWithIdentifier("categoryCell") as! categoryCell

will return you the cell for reuse but you need to access the currently loaded cell at indexPath where user tapped :) So use cellForRowAtIndexPath. cellForRowAtIndexPath returns the currently loaded cell at indexPath