1

我有一个自定义 UITableView 单元,我选择了一个特定的单元并转到另一个 ViewController,当我回到第一个视图控制器时,单元的选定状态不可见。从另一个视图控制器导航后,我将如何更改单元格的选定状态?

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   return [timeSet count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   timeSettingCell *newCell = nil;
   newCell = [tableView dequeueReusableCellWithIdentifier:identifier];
   if(newCell == nil)
   {
    NSLog(@"newCell ===================");
    NSArray *nibViews = [[NSBundle mainBundle] loadNibNamed:@"timeSettingCell"   owner:self options:nil];
    newCell  = [ nibViews lastObject];
    }
    newCell.timeLabel.text=[timeSet objectAtIndex:indexPath.row];

    if (newCell.selected==YES) {
      newCell.highlighted=YES;
      newCell.timeImage.image=[UIImage imageNamed:@"radioSelected.png"];
    }
    else {
      newCell.highlighted=NO;
      newCell.timeImage.image=[UIImage imageNamed:@"radioNotSelected.png"];
    }
return newCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
value=[[time1 objectAtIndex:indexPath.row]integerValue];

SettingsViewController *settings=[[SettingsViewController alloc]initWithNibName:nil bundle:nil andCounterValue:value];
[[self presentingViewController] dismissModalViewControllerAnimated:YES];
index=indexPath.row;
[settings release];
}
-(void)viewWillAppear:(BOOL)animated{
}

谢谢你

4

2 回答 2

2

像这样放,它会工作得很好......

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

[tableView deselectRowAtIndexPath:indexPath animated:YES];
于 2012-04-05T09:08:11.873 回答
1

我认为您应该使用创建为单例、ivar 或 NSUserDefault 的 NSArray 来记住您的单元格状态(已选择或未选择),然后在cellForRowAtIndexPath.

编辑:示例代码

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Do what you want

// This save the index of your selected cell on disk
[[NSUserDefaults standardUserDefaults] setInteger:indexPath.row forKey:@"selectedCell"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Create your cell

// Here you check if the cell should be selected or not
if (indexPath.row == [[NSUserDefaults standardUserDefaults] integerForKey:@"selectedCell"]) {
    newCell.highlighted=YES;
    newCell.timeImage.image=[UIImage imageNamed:@"radioSelected.png"];
} else {
    newCell.highlighted=NO;
    newCell.timeImage.image=[UIImage imageNamed:@"radioNotSelected.png"];
}

return aCell;
}

NSUserDefaults对于在您的设备上保存数据并稍后检索它们很有用。这意味着即使在关闭并重新打开您的应用程序后,您也可以检查您的单元格状态。

要使用NSUserDefaults,您需要将 Settings.bundle 添加到您的项目中。看看NSUserDefaults 类参考

于 2012-04-05T08:13:26.357 回答