我希望能够更改单个UITableView单元格的颜色。在我的tableView(editActionsForRowAtIndexPath)中,我可以滑动单元格并选择一个按钮来更改背景颜色但是当我在屏幕上滚动单元格时它会改变回来。如何保持颜色?感谢
答案 0 :(得分:2)
假设tableView中只有一个部分有很多行,你需要在tableView中执行此操作:cellForRowAtIndexPath:method:
if (indexPath.row == coloredCellIndex) {
cell.backgroundColor = UIColor.RedColor()
} else {
cell.backgroundColor = UIColor.WhiteColor()
}
您需要在此函数之外的任何位置设置变量coloredCellIndex,例如在viewDidLoad
中答案 1 :(得分:0)
抱歉,我只能在Objective-C中写下我的答案。但我希望你能明白我的观点。
如果您使用的是自定义原型单元格,则可以将属性添加到自定义表格视图单元格类中,并存储该单元格所需的当前颜色,然后再重新加载该颜色。
示例代码:
在CustomTableViewCell.h中
@interface CustomTableViewCell : UITableViewCell
@property (nonatomic) UIColor *cellColor;
- (void)reloadBackgroundColor
@end
在CustomTableViewCell.m
中- (void)reloadBackgroundColor
{
self.backgroundColor = cellColor; //this is just a sample.
}
然后在每次重新加载单元格时都可以设置该颜色。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
CustomTableViewCell *tableCell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomTableCellIdentifier"];
[tableCell reloadBackgroundColor];
return tableCell;
现在,每次滚动表格时,都会加载要设置为该单元格的颜色。
如果您没有使用自定义原型单元格,那么我建议您将每个单元格所需的颜色存储在字典中,并将其索引作为键。然后,每次重新加载时,只需将它再次分配给该单元格。
我希望这会对你有所帮助。 :)
答案 2 :(得分:-1)
Swift 3
viewDidLoad中
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
cellForRowAt
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 }