0

这是我在 Storyboards 中的项目结构:

导航视图控制器 ------> 主视图控制器 ------> 2 个子视图控制器

两个子视图控制器中的每一个都有一个单独的表和视图控制器。

下面的代码工作得很好,但我面临的问题是,可以说我在这个表中选择索引 2(会出现一个复选标记图像):它将带我到主 ViewController,但如果我从主 ViewController点击一个按钮导航到另一个子视图,该子视图打开时已在索引 2 处显示复选标记图像(反之亦然)。

这是我的 ChildViewController 之一的代码:

#import "MainVC"
#import "ChildVC"
@interface ChildVC ()
@end

@implementation ChildVC

NSIndexPath *lastIndexPath;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    tableArr =[[NSMutableArray alloc] initWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"Other",nil];
    self.navigationItem.leftBarButtonItem=nil;
    self.navigationItem.hidesBackButton=YES;
    self.navigationItem.title = @"Select Language";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{        
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,10, 300, 30)];
    [cell.contentView addSubview:label];
    label.text = [tableArr objectAtIndex:indexPath.row];
    label.tag = 1;
    label.textColor = [UIColor colorWithRed:47.0f/255.0f green:111.0f/255.0f blue:182.0f/255.0f alpha:1.0f];
    UIImageView *checkmark = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"coloredCheckmark.png"]];
    cell.accessoryView = checkmark;
    return cell;
}

- (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath 
{    
    lastIndexPath = indexPath;
    [tableView reloadData];

    // Here I am sending the Value of Selected Row to Main View Controller and storing in typelabel.text
    UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath];
    UILabel *lbltemp = (UILabel *)[cell1 viewWithTag:1];
    _parent.typelabel.text = lbltemp.text;

    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 9;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell      forRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if ([lastIndexPath isEqual:indexPath]) {
        cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iphone-checkMark.png"]];
    } else {
        cell.accessoryView = nil;
    }
} 

@end
4

0 回答 0