Iphone 如何使用UIActionSheet更改自定义UITableViewCell的颜色?

Iphone 如何使用UIActionSheet更改自定义UITableViewCell的颜色?,iphone,objective-c,ios,ipad,Iphone,Objective C,Ios,Ipad,我有一个包含多行的TableView。每行具有不同的自定义UITableViewCell。我需要在UIActionSheet的帮助下更改此单元格的颜色。这意味着当我选择一行时,会弹出一个操作表,要求为单元格选择特定的颜色。另一件重要的事情是,即使电池离开屏幕,电池也应该保持颜色 这是我的密码。我的代码的问题是单元格没有得到实时更新。如果再次选择该行,单元格的颜色将更新。另一个问题是,如果向下滚动,单元格颜色将更改为默认白色 UIColor *cellColour; -(void)tableVi

我有一个包含多行的TableView。每行具有不同的自定义UITableViewCell。我需要在UIActionSheet的帮助下更改此单元格的颜色。这意味着当我选择一行时,会弹出一个操作表,要求为单元格选择特定的颜色。另一件重要的事情是,即使电池离开屏幕,电池也应该保持颜色

这是我的密码。我的代码的问题是单元格没有得到实时更新。如果再次选择该行,单元格的颜色将更新。另一个问题是,如果向下滚动,单元格颜色将更改为默认白色

UIColor *cellColour;

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    switch (indexPath.row)
       {
        case 0:
            [self displayActionSheet];
            cell.backgroundColor=cellColour;
            break;
        case 1:
            cell.backgroundColor=[UIColor yellowColor];
            break;
        default:
            break;
    }
}

-(void) displayActionSheet
{
    UIActionSheet *popupQuery = [[UIActionSheet alloc] initWithTitle:@"Select row colour"   delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Red",@"Green",nil];

    popupQuery.actionSheetStyle = UIActionSheetStyleDefault;

    [popupQuery showInView:self.view];

    [popupQuery release];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
switch (buttonIndex)
    {
      case 0:
        NSLog(@"Red");
        cellColour=UIColor.redColor;
        break;
      case 1:
        NSLog(@"Green");
        cellColour=UIColor.greenColor;
        break;
      case 2:
        NSLog(@"Pressed Cancel");
        cellColour=nil;
        break;
      default:
        break;
    }   
}

请帮助。

这是正常的,因为
UIActionSheet
行为是异步的

当您调用
displayActionSheet
时,它会在屏幕上显示
UIActionSheet
,然后继续执行代码(无需等待用户点击操作表的按钮)。然后,当用户点击操作表的一个按钮时,将调用委托方法
actionSheet:clickedbuttonationindex:

您需要做的是:

  • 使用
    tableView:cellforrowatinexpath:
    方法中的
    cellColor
    属性(我希望它实际上是类的
    @property
    ,而不是像您问题中的代码那样的全局变量!!!)设置
    cell.backgroundColor=cellColour;
    此处)因此,每次重复使用单元格并在屏幕上显示时都会使用颜色
  • 操作表中调用
    [tableView reloadData]
    :ClickedButtonIndex:
    委托方法,在用户在操作表中选择颜色时重新加载tableView,以便更新单元格颜色

请编辑您的帖子以更正代码格式。我尝试了所有方法。还没有运气。您能否提供一些示例代码?您是否尝试使用
selectedBackgroundView
属性来影响背景填充颜色的全新
UIView
?或者重写自定义
UITableViewCell
setSelected:
方法-(void)tableView:(UITableView*)tableView将显示cell:(UITableViewCell*)单元格for rowatindexpath:(nsindepath*)indepath{if(indepath.row==0){cell.backgroundColor=alertviewcellcolor;}if(indexath.row==1){cell.backgroundColor=ActionSheetCellColor;}}我使用了上面的代码来设置背景颜色单元格。它现在运行良好。但不确定它是否是一种优化的方法。谢谢你的帮助,伙计。我希望代码符合我的要求。我想说,如果它运行正常,这是一种好的方法。选择单元格的状态可能与您尝试手动设置的背景颜色不一致。您可以尝试调用[
tableView DecelrowatingIndexPath:indexPath]
表格视图:didSelectRowAtIndexPath:
中,确保修改背景色的标准选择系统不会与您自己修改背景色的代码混淆。