单击特定单元格时,如何向另一个 viewcontroller 显示表格视图单元格的数据?

How to show the data of a tableview cell to another viewcontroller when clicking on that particular cell?

我是 iOS 开发的新手。我正在构建一个基本项目,其中有两个视图控制器。在其中一个中,我有一个 tableView,在另一个中,我有一个标签和一个文本字段。在 tableview 中,我使用了一个自定义单元格,并在其中使用了两个标签。在这两个标签中,我分配了两个数组。现在我想将这两个数组的数据显示到另一个视图控制器的标签和文本字段。所以我想知道在didSelectRowAtIndexPath方法中要写什么代码。

这是我完成的代码。

#import "TabViewController.h"

@interface TabViewController ()

@end

@implementation TabViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.peoplenames = @[@"Soumen Da" ,@"Debu Da" ,@"Sandipan Da" ,@"Pradipta Da" ,@"Sandeep Da" ,@"Pran Da" ,@"Amit Da" ,@"Piyali Di" ,@"Niladri Da" ,@"Biswa Da", @"Soumitra Da" ,@"Utpal Da", @"Sandip Da"];

    self.peopleaddress = @[@"Santragachhi" ,@"Kolkata" ,@"Shambazar" ,@"Jadavpur" ,@"Saltlake" ,@"New Town" ,@"Beleghata" ,@"Garia" ,@"Barakpur" ,@"Naihati" ,@"Agarpara" ,@"Sodpur" ,@"Park Street"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];


    UILabel *lbl1 = (UILabel*)[cell.contentView viewWithTag:2];
    lbl1.text = [self.peoplenames objectAtIndex:indexPath.row];
    NSLog(@"row===%ld",(long)indexPath.row);

    UILabel *lbl2 = (UILabel*)[cell.contentView viewWithTag:1];
    lbl2.text = [self.peopleaddress objectAtIndex:indexPath.row];
    NSLog(@"row===%ld",(long)indexPath.row);

    return cell;

}

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

    [self performSegueWithIdentifier:@"detail" sender:self];

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [self.peoplenames count];


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Blockquote

您可以将 table 单元格的 segue 放到下一个视图控制器中,而无需在 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath.

中做任何事情

在第一个视图控制器中使用 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 和 table 视图并访问 segue.destinationViewController.label 和 segue.destinationViewController.label.textField 以将值传递给第二个视图控制器。

如果你想在 didSelectRowAtIndexPath 中执行以下操作。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 UIStoryboard *sb=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        DetailViewController *vc=(DetailViewController *)[sb instantiateViewControllerWithIdentifier:@"detail"];
        vc.label.text =[self.peopleaddress objectAtIndex:indexPath.row];
vc. textfield.text =[self.peopleaddress objectAtIndex:indexPath.row];

}