Reputation: 3110
Disclaimer: I'm on iOS 8, so there's a chance this is a bug.
I'm attempting to programmatically edit the backgroundColor of a cell at a particular IndexPath in a UITableView after a particular event. I use the following code:
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithRed:1 green:0.84 blue:0 alpha:1];
While this works well, as soon as I scroll, I see other cell(s) with the changed background color. I think it has something to do with the following code in my - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
method:
static NSString *simpleTableIdentifier = @"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
...
I suspect since all cells are generated with this identifier, somehow the properties are getting confused (though the style doesn't then apply to everything, only random cells, so that's points against this theory). Thanks for the help!
Upvotes: 0
Views: 220
Reputation: 1160
Let's say you want to make cell selectable and unselectable do this:
var selected = [Int:Int]()
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! YourCellTypeClass
//check if the cell button is selected
if((selected[indexPath.row]) != nil){
cell.backgroundColor = UIColor.blueColor()
}else{
cell.backgroundColor = UIColor.whiteColor()
}
return cell;
}
func selectCell(index: Int){
let indexPath = NSIndexPath(forRow: index, inSection: 0)
let cell = tableView.cellForRowAtIndexPath(indexPath) as! YourCellTypeClass
if((selected[index]) != nil){
cell.backgroundColor = UIColor.blueColor()
selected[index] = nil
print("unselected: \(index)")
}else{
ccell.backgroundColor = UIColor.redColor()
selected[index] = index
print("selected: \(index)")
}
}
Upvotes: 0
Reputation: 15015
One way you can change the background color like that below. For example you want to change alternate row color :-
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row%2== 0) {
[cell setBackgroundColor:[UIColor yellowColor]];
}
else {
[cell setBackgroundColor:[UIColor whiteColor]];
}
Upvotes: 0
Reputation: 318824
You need to change the background for all cells.
if (/* some condition for special background color */) {
cell.backgroundColor = ... // special background color
} else {
cell.backgroundColor = ... // normal background color
}
This avoid the reuse issue. You must follow this pattern for any cell attribute you wish to set differently for certain cells.
Upvotes: 1