Ok. I cant seem to get a firm understanding on how tableviews work. Would someone please explain to me how cells are reused in tableviews especially when scrolling? One of t
Swift 2.1 version of accepted answer. Works great for me.
override func viewDidLoad() {
super.viewDidLoad();
self.arrayProducts = NSMutableArray(array: ["this", "that", "How", "What", "Where", "Whatnot"]); //array from api for example
var i:Int = 0;
for (i = 0; i<=self.arrayProducts.count; i++){
let numb:NSNumber = NSNumber(bool: false);
self.arrayFavState.addObject(numb); //array of bool values
}
}
TablView Datasource methods ::
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SubCategoryCellId", forIndexPath: indexPath) as! SubCategoryCell;
cell.btnFavourite.addTarget(self, action: "btnFavouriteAction:", forControlEvents: UIControlEvents.TouchUpInside);
var isFavourite: Bool!;
isFavourite = self.arrayFavState[indexPath.row].boolValue;
if isFavourite == true {
cell.btnFavourite.setBackgroundImage(UIImage(named: "like-fill"), forState: UIControlState.Normal);
} else {
cell.btnFavourite.setBackgroundImage(UIImage(named: "like"), forState: UIControlState.Normal);
}
return cell;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrayProducts.count;
}
Button Action method ::
func btnFavouriteAction(sender: UIButton!){
let position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableProducts)
let indexPath = self.tableProducts.indexPathForRowAtPoint(position)
let cell: SubCategoryCell = self.tableProducts.cellForRowAtIndexPath(indexPath!) as! SubCategoryCell
//print(indexPath?.row)
//print("Favorite button tapped")
if !sender.selected {
cell.btnFavourite.setBackgroundImage(UIImage(named: "like-fill"), forState: UIControlState.Normal);
sender.selected = true;
self.arrayFavState.replaceObjectAtIndex((indexPath?.row)!, withObject:1);
} else {
cell.btnFavourite.setBackgroundImage(UIImage(named: "like"), forState: UIControlState.Normal);
sender.selected = false;
self.arrayFavState.replaceObjectAtIndex((indexPath?.row)!, withObject:0);
}
}