I want to be able to change the color of a single UITableView cell. In my tableView(editActionsForRowAtIndexPath) I can swipe the cell and select a button to change the background color but when I scroll the cell off screen it changes back. How do I get it to retain the color? Thanks
Assuming you have only one section in your tableView with many rows, you need to do this in your tableView:cellForRowAtIndexPath: method:
if (indexPath.row == coloredCellIndex) {
cell.backgroundColor = UIColor.RedColor()
} else {
cell.backgroundColor = UIColor.WhiteColor()
}
You need to set the variable coloredCellIndex anywhere outside of this function, for example in viewDidLoad
Sorry, I can only write my answer in Objective-C. But I hope you can get my point.
If you are using a custom prototype cell, then you can add a property to your custom table view cell class, and store the current color you want for that cell, and then later in reload that color.
Sample code:
In CustomTableViewCell.h
@interface CustomTableViewCell : UITableViewCell
@property (nonatomic) UIColor *cellColor;
- (void)reloadBackgroundColor
@end
In CustomTableViewCell.m
- (void)reloadBackgroundColor
{
self.backgroundColor = cellColor; //this is just a sample.
}
And then under you can just set that color everytime the cell is reloaded.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
CustomTableViewCell *tableCell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomTableCellIdentifier"];
[tableCell reloadBackgroundColor];
return tableCell;
Now, everytime you scroll the table, the color you want to set to that cell will be loaded.
If you are not using a custom prototype cell, then I suggest that you store the color you want for each cell in a Dictionary, with its index as the key. Then you just assign it again to that cell every time it is reloaded.
I hope this helps you. :)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
cell.backgroundColor = .black
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:CustomTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "myCell") as! CustomTableViewCell cell.accessoryType = .none cell.backgroundColor = .black return cell }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.