Ios cellForRowAtIndexPath属性更改更改多个单元格

Ios cellForRowAtIndexPath属性更改更改多个单元格,ios,objective-c,uitableview,Ios,Objective C,Uitableview,免责声明:我使用的是iOS 8,所以这可能是一个bug。 我试图在特定事件发生后,以编程方式编辑UITableView中特定IndexPath处单元格的背景色。我使用以下代码: UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; cell.backgroundColor = [UIColor colorWithRed:1 green:0.84 blue:0 alpha:1]; 虽然效果很好,但我一滚动,就会看

免责声明:我使用的是iOS 8,所以这可能是一个bug。

我试图在特定事件发生后,以编程方式编辑UITableView中特定IndexPath处单元格的背景色。我使用以下代码:

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithRed:1 green:0.84 blue:0 alpha:1];
虽然效果很好,但我一滚动,就会看到其他单元格的背景颜色发生了变化。我认为这与我的
-(UITableViewCell*)tableView:(UITableView*)tableView cellforrowatinexpath:(nsindepath*)indepath
方法中的以下代码有关:

static NSString *simpleTableIdentifier = @"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
...

我怀疑,由于所有的单元格都是用这个标识符生成的,所以属性不知何故变得混乱了(尽管这种样式并不适用于所有的单元格,只适用于随机单元格,所以这是反对这种理论的观点)。谢谢你的帮助

您需要更改所有单元格的背景

if (/* some condition for special background color */) {
    cell.backgroundColor = ... // special background color
} else {
    cell.backgroundColor = ... // normal background 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]];
}

假设要使单元格可选择和不可选择,请执行以下操作:

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)")
    }


}

我想你的意思是在
tableView…cellforrowatinexpath…
方法中?如果是这样,那么每次我想更改单个单元格上的属性时都需要重新加载tableView,不是吗?编辑我想我理解你的意思…所以我应该为新单元格设置默认背景色,但也应该根据是否发生改变单元格颜色的事件设置背景色。我会试试这个……是的,在
cellForRow…
中。不,这并不意味着你需要重新加载表视图,永远。@RubenMartinezJr.-您可以使用
reloadRowsAtIndexPaths
只重新加载表的一部分。我认为这是可行的!我正在像以前一样设置事件的背景色,但在
表视图…cellforrowatinexpath…
中也有此if条件。当加载行时,它们会检查该行是否触发了我的事件。如果是,请采用背景色!谢谢决不应更改cellForRowAtIndexPath之外单元格的内容。当单元格从视图中滚出并返回视图时,它们会被“回收”,任何未在该方法中进行的更改都会在滚动时消失。