iOS:数据在传递给另一个 ViewController 后消失

Posted

技术标签:

【中文标题】iOS:数据在传递给另一个 ViewController 后消失【英文标题】:iOS: data disappear after passing it to another ViewController 【发布时间】:2013-11-04 15:14:03 【问题描述】:

我的应用程序有问题。 当我以这种方式将 UIView 传递给 SecondViewController 时

SecondViewController *second = [self.storyboard instantiateViewControllerWithIdentifier:@"secondviewcontroller"];
second.currentView = currentView;

(second.currentView 是我在 SecondViewController 中的属性,我将视图传递给它)

此时,一切正常,我的 SecondViewController 正确显示了我的 currentView,但是当我在 FirstViewController 中返回时,我的 currentView 消失了!!! 为什么?你能帮助我吗?谢谢

更新

在 FirstViewController.h 中

IBOutlet UIView *currentView;

在 FirstViewController.m 中

SecondViewController *second = [self.storyboard instantiateViewControllerWithIdentifier:@"secondviewcontroller"];
second.currentView = currentView;
[self presentViewController:second animated:NO completion:nil];

在 SecondViewController.h 中

@property (nonatomic, strong) UIView *currentView;

在 SecondViewController.m 中

- (void) viewDidAppear:(BOOL)animated
[self.view addSubview:self.currentView];
self.currentView.center = CGPointMake(self.view.bounds.size.width/2,   self.view.bounds.size.height/2);

这是我在两个 ViewController 中的代码,当我在 FirstViewController currentView 中返回时,没有……它消失了……

【问题讨论】:

是的,我更新了我的问题 是的,我使用dismissViewController 我认为最好的解决方案是在 appDelegate 中使用全局变量,这样我就解决了我所有的问题 我试过了,还是没有解决我的问题 这只是 [self dismissViewControllerAnimated:NO completion:nil];在 IBAction 内 【参考方案1】:

视图只有超级视图,因此当您将视图添加到 SecondViewController 时,您需要将其添加到其视图层次结构中,从而从当前视图控制器中删除。当你打电话时:

- (void) viewDidLoad
    [super viewDidLoad];
    // Here the view is removed the first view and placed on the second view.
    [self.view addSubView:self.secondView];

因此,如果您想将其重新添加到第一个视图中,您需要再次将其添加到第一个视图的视图层次结构中。

更好的 解决方案是将数据传递给下一个视图控制器,而不是视图,而是模型。就像传递包含视图中呈现的数据的模型对象一样。

【讨论】:

你能给我举个例子吗? 不,因为我不知道您尝试在两个视图控制器之间共享的数据。您也应该尝试自己解决问题。 这个答案是正确的,当您将第一个视图控制器的视图设置为第二个控制器时,您将从第一个控制器中删除它。此外,传递视图是一件奇怪的事情,因此您可能会尝试解释您到底想做什么。【参考方案2】:

我的问题解决了!!!

当我在 FirtsViewController 中返回时,我必须在我的 self.view 的最后一个位置添加一个新的时间视图,以这种方式:

[self.view addSubview:currentView];

[currentView setCenter:initially_center_view];

这样我就看到了我的观点!!!

【讨论】:

以上是关于iOS:数据在传递给另一个 ViewController 后消失的主要内容,如果未能解决你的问题,请参考以下文章

如何在ios中自定义推送和弹出动画时将视图传递给另一个控制器? [关闭]

使用没有 segues 的协议将数组从 appDelegate 传递到 Viewcontroller

Swift 3 - 在视图控制器之间传递数据,然后再传递给另一个 2

如果*** UIView 没有收到它想要处理的手势,则将手势/触摸传递给另一个 UIView?

IOS7 tableview底部viewcontrol中的多余空间

在 swift 5.2 con Alamofire 中将数据(json)传递给另一个控制器