【问题标题】:Passing data to a view controller different when the controller is presented modally?当控制器以模态方式呈现时,将数据传递给不同的视图控制器?
【发布时间】:2014-01-17 04:31:57
【问题描述】:

我对 iOS 的东西还很陌生,我认为我理解将数据传递给视图控制器。显然不是。我正在尝试将图像数据从父 ViewController 传递给以模态方式呈现的子 ViewController。我认为问题与将对象传递给模态呈现的视图控制器而不是推送到导航堆栈的方式有关。贝娄是父母和孩子与我遇到的问题相关的代码。

来自 Parent.m:

- (IBAction)sort:(id)sender {
    SortSelectViewController *ssvc = [self.storyboard instantiateViewControllerWithIdentifier:@"sort"];
    ssvc.backgroundImage = [self screenshot];
    [self performSegueWithIdentifier:@"sort" sender:self];
    //The segue is linked from my parent view controller to my child with the identifier "sort"

}

- (UIImage *) screenshot {
    CGRect rect = CGRectMake(0, 20, 640, 1116);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);

    [self.view drawViewHierarchyInRect:rect afterScreenUpdates:YES];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    return image;
}

这是在我的 Child.h 中

@property (nonatomic, strong) UIImage *backgroundImage;

这是我的 Child.m:

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSLog(@"%@", self.backgroundImage);
    //This log will return nil when the program is run - clear sign data is not being correctly passed
    self.backgroundImage = [self.backgroundImage applyDarkEffect];
    self.imageView.image = self.backgroundImage;
}

我已经将我的子视图控制器导入到我的父类中

【问题讨论】:

标签: ios modalviewcontroller


【解决方案1】:

您的代码(原始问题)将视图控制器的直接实例化和情节提要 segues 混为一谈。当您使用故事板转场时,VC 会自动为您实例化。您可以在“prepareForSegue:”方法中将其作为“目标视图控制器”访问。

发生的情况是,您实例化了一个视图控制器,设置了图像,然后……它被丢弃并被忽略(整个 vc)。

接下来,您启动一​​个 segue,iOS 通过实例化 另一个 不同的视图控制器来处理它。 iOS 呈现的就是这个视图控制器。

所以:如果您要使用 Storyboard segue,iOS 会为您实例化 VC。不要自己实例化一个,因为没有办法将 you 实例化到 iOS segue 处理中。您实例化的是一个无关紧要的额外内容,会被忽略。

【讨论】:

  • 太棒了。很好的解释。这就是我要找的东西!
【解决方案2】:

try Like this 通过使用 Story Bord 必须使用两种方法的组合 performSegueWithIdentifier: *prepareForSegue:*

    - (IBAction)sort:(id)sender {

        [self performSegueWithIdentifier:@"sort" sender:self];
        //The segue is linked from my parent view controller to my child with the identifier "sort"

    }



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

        if ([[segue identifier] isEqualToString:@"sort"])
        {
           SortSelectViewController *ssvc = [segue destinationViewController];
        ssvc.backgroundImage = [self screenshot];
        }
     }

- (UIImage *) screenshot {
       //return normal image 
    return [UIImage imagenamed:"imagename.png"];
}

【讨论】:

  • 编辑:抱歉,我没有将初始化视图控制器的方法更改为那个。这行得通,但为什么我不能通过按下按钮来完成这一切?
猜你喜欢
  • 1970-01-01
  • 2011-01-20
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
相关资源
最近更新 更多