使用Segue(Objective-C)将数据从UITableView传递到目标ViewController

时间:2016-06-18 18:47:23

标签: ios objective-c

我试图将tableviewcell的数据传递到目标ViewController,其中我有一个标签,我想在选择特定单元格时使用segue将该数据设置为标记文本。

4 个答案:

答案 0 :(得分:2)

您可以使用以下方法:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"SegueName"]) {
        //Create Object/Variable in destination ViewController and assign here 
    } }

你可以查看Demo @ http://www.appcoda.com/storyboards-ios-tutorial-pass-data-between-view-controller-with-segue/

答案 1 :(得分:1)

只需在原始视图控制器的.m文件中声明一个全局变量来存储数据,并在目标视图控制器中声明相同类型的属性,然后将该数据存储在-prepareForSegue方法的属性中

您的代码应如下所示:

@implementation OriginViewController
{
  ObjectType *object;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    object = // whatever value you want to store
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue
{
    DestinationViewController *destVC = [segue destinationViewController];
    [destVC setProperty:object];
}

答案 2 :(得分:1)

非常简单:

RELEASE

这意味着:

  1. 您的表格视图已启用选择
  2. 您的目标视图控制器具有属性- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:<#whatever#>]) { NSIndexPath * selectedIndexPath = [tableView indexPathForSelectedRow]; // get from your data source the data you need at the index path YourVC * destVC = [segue destinationViewController]; destVC.selectedData = data; } }
  3. 您有一个从原型表视图单元格到目标视图控制器的segue

答案 3 :(得分:0)

@property (strong, nonatomic) NSIndexPath *selectedRow; // set a default value of nil in viewDidLoad method

现在只需使用此逻辑将数据从UITableView传递到任何UIViewController

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    selectedRow = indexPath;
    //now simply invoke this method to perform segue.
    [self performSegueWithIdentifier:@"Your-Identifier" sender:self];
}

检查您的segue标识符,然后传递数据。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"Your-Identifier"]) {
            UIViewController *viewController = segue.destinationViewController;
            //Your current selected cell path is stored in selectedRow if you have save value in any Array you can fetch it like this...
            viewController.firstName = [arrayOfFirstNames objectAtIndex:selectedRow.row];
            //Or You can access the tableView cell by this method.
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:selectedRow];
        }

}