使用segue(Objective-c)将数据从UITATIONVIEW传递到目标视图controller



我正在尝试将tableViewCell的数据传递到具有标签的目标viewController,我想在选择特定的单元格时使用SEGUE将该数据设置为标签文本。

您可以使用下面的方法:

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

您可以检查演示 @http://www.appcoda.com/storyboards-ios-tutorial-pass-data-data-weien-view-controller-with-segue/

只需在您的Origin View Controller的.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];
}

它真的很简单:

- (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;
    } 
}

这意味着:

  1. 您的表视图具有选择启用
  2. 您的目标视图控制器具有属性-selectedData
  3. 您有一个从原型表视图单元格到目标视图控制器
  4. 开始的segue
@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];
        }
}

相关内容

最新更新