我有一个包含多行的 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/