问题描述
TL; DR:我需要实现一个在多个ViewControllers之间共享的单例UIWebVIew。这个问题包含到目前为止的所有方法。
TL;DR: I need to implement a singleton UIWebVIew that's shared across multiple ViewControllers. The question contains all of my approaches so far.
appDelegate:
@property (strong, nonatomic) UIWebView *singleWebView;
firstViewController:
@property (weak, nonatomic) IBOutlet UIWebView *webView;
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear: animated];
NSLog(@"Removing webview from the first VC");
[self.webView removeFromSuperview];
self.webView.delegate = nil;
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.singleWebView = self.webView;
self.webView = nil;
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *URL = [request URL];
if ([[URL absoluteString] isEqualToString:@"myapp://postsShow"]) {
[self performSegueWithIdentifier:@"postsShowSegue" sender:self];
return false;
}
return true;
}
PostsShowViewController
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[self.viewContainer addSubview: appDelegate.singleWebView];
}
在第一个视图控制器中,我加载了我的单页应用,显示了首先列出帖子。然后,用户查看其中一个帖子,他将被重定向到第二个视图控制器。我想重用第二个ViewController中第一个ViewController中使用的UIWebView,所以我不必重新加载网页。
In the first view controller, I load my single page app, which shows a list of posts first. Then, the user views one of the posts and he will be redirected to the second View Controller. I want to reuse the UIWebView that was used in the first ViewController in the second ViewController so I don't have to reload the webpage.
问题是,在 addSubview
之后,似乎没有加载UIWebView。我只看到我用作容器的 UIView
。如果你能给我一些调试点,那将非常有帮助。
The problem is that, after addSubview
the UIWebView doesn't seem to be loaded. I only see a UIView
that I use as a container. It would be really helpful if you could give me some debugging points.
推荐答案
我终于想通了。即使我从 FirstViewController
中删除 UIWebView
实例后,保留计数始终为2。我从故事板中删除了 UIWebView
,并在加载 firstViewController
时以编程方式创建它。我把其他一切都保留了下来。最后我可以开始重用 webView
。
I finally figured out. The retain count was always 2, even after I removed the UIWebView
instance from the FirstViewController
. I removed the UIWebView
from the storyboard and created it programmatically when the firstViewController
was loaded. I left everything else the same. Finally I could start reusing the webView
.
这篇关于在不同的viewControllers中使用相同的UIWebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!