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

标签 iphone objective-c ios ipad

我有一个包含多行的 TableView。每行都有不同的自定义 UITableViewCell。我需要借助 UIActionSheet 更改此单元格的颜色。这意味着当我选择一行时,应该弹出一个 Actionsheet 要求为单元格选择特定的颜色。另一个重要的事情是,即使单元格离开屏幕,单元格也应该保留颜色。

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

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 然后继续执行代码(无需等待用户点击操作表的按钮)。然后当用户点击操作表的按钮之一时,委托(delegate)方法 actionSheet: clickedButtonAtIndex: 被调用。

你需要做的是:

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

关于iphone - 如何使用 UIActionSheet 更改自定义 UITableViewCell 的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12438960/

相关文章:

ios - 配置单元格时更改 View 位置。奇怪的行为

ios - 从 inputView 获取 UItextField

ios - 如何将 iPhone 应用程序中的 Web View 映射到 Apple Watch 应用程序

objective-c - 是否可以在不失去其他背景窗口焦点的情况下将焦点集中在 NSPanel 上?

objective-c - 通过有线通信将网络摄像头类型的摄像机传输到 iPad2

ios - 在 iOS 应用程序中保存和显示视频。

ios - 以编程方式在 UIScrollview 中添加多个 UIImageview

iphone - 在某个时间创建表示 "today"的 NSDate 对象

iphone - Xcode4:依赖项目和构建配置

android - 在 Android 和 IOS 上管理图像