我使用 aUITableView
作为首选项屏幕,其中行代表用户选择。
我正在使用NSUserDefaults
. 我的问题是我正在尝试为单元格创建一个特殊的外观,我通过构建一种特殊的颜色并在以下代码中使用它来做到这一点:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
}
cell.textLabel.text = [myArray objectAtIndex:[indexPath row]];
UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor colorWithRed:(200/255.0) green:(200/255.0) blue:(200/255.0) alpha:0.6];
cell.selectedBackgroundView = selectionColor;
cell.textLabel.textColor = [UIColor grayColor];
return cell;
}
基于此,当发生用户点击时,它会显示我在此事件中构建的浅灰色,这就是我想要的。当用户取消选择它时,灰色的背景颜色就消失了。
现在我需要添加NSUserDefaults
, 以检查该单元格是否已保存。事件现在变成了这样:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
}
cell.textLabel.text = [myArray objectAtIndex:[indexPath row]];
UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor colorWithRed:(200/255.0) green:(200/255.0) blue:(200/255.0) alpha:0.6];
cell.selectedBackgroundView = selectionColor;
cell.textLabel.textColor = [UIColor grayColor];
if([[NSUserDefaults standardUserDefaults] valueForKey:selectedOption]) {
//Here, how can I make the cell look grayish in the background?
//If I do cell.selected = true// the cell shows a black background color
}
return cell;
}
如果我称cell.selected = true
该单元格有黑色背景,而不是我真正想要的。我不知道应该在哪里执行此自定义。
更新:按照 rdelmar 的回答,我更新了 cellForRowAtIndexPath 并添加了自定义代码
if (myArray[indexPath.Row][selectionState] == YES){
UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor colorWithRed:(200/255.0) green:(200/255.0) blue:(200/255.0) alpha:0.6];
cell.selectedBackgroundView = selectionColor;
cell.textLabel.textColor = [UIColor grayColor];
}else{
cell.selectedBackgroundView = nil;
cell.textLabel.textColor = [UIColor blackColor];
}
仍然没有;'r解决了这个问题,这意味着它将通过验证l(selectionState == yes,并点击代码更改背景视图的颜色,但显示时它仍然保持不变。
我找到了这个方法willDisplayCell,我把关于定制的代码移到那里,仍然没有工作!
- (UITableViewCell *)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (myArray[indexPath.Row][selectionState] == YES){
UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor colorWithRed:(200/255.0) green:(200/255.0) blue:(200/255.0) alpha:0.6];
cell.selectedBackgroundView = selectionColor;
}
else{
cell.selectedBackgroundView = nil;
cell.textLabel.textColor = [UIColor blackColor];
}
return cell;
}
我应该拦截另一个事件或方法吗?