OGeek|极客世界-中国程序员成长平台

标题: iphone - 为什么我的应用内浏览器没有加载? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 16:25
标题: iphone - 为什么我的应用内浏览器没有加载?

我想创建一个自定义应用内浏览器以在我的应用内显示它。

我的架构如下所示: UIViewController 的子类:uiviewcon 从它的 Nib 加载:

在我实例化 uiviewcon 之后,我在上面调用以下方法:

-(void)loadrequestNSURLRequest *)urlrequest{
    [webView loadRequest:urlrequest];
}

webview 是我 Nib 中 UIWebView 的 IBOutlet。但是似乎 webView 是 nil (我通过 if(webView)... 进行了检查,并且我肯定已经在 IB 中连接了它)

我的 webView 没有被分配的可能原因是什么?我也在 uiviewcon 中实现了 UIWebViewDelegate 协议(protocol)的一些方法(在 uiviewcon 的 viewDidLoad 中将 self 设置为委托(delegate)),但这些方法都没有被调用(似乎合理,因为 webView 为 nil)。

如何改进我的代码,以便我的浏览器最终加载一些东西?

编辑:我的 uiviewcon 标题:

@protocol CustomWebViewDelegate
-(void)hidecustomwebview;
@end

@interface CustomWebView : UIViewController<UIWebViewDelegate> {
    UIActivityIndicatorView *spinner;
    UIWebView *webView;
}
@property (nonatomic, retain) IBOutlet UIActivityIndicatorView *spinner;
@property (nonatomic, retain) IBOutlet UIWebView *webView;
@property (nonatomic,assign) id <CustomWebViewDelegate>delegate;
-(void)webViewDidStartLoadUIWebView *)webView;
-(void)webViewDidFinishLoadUIWebView *)webView;
-(void)loadrequestNSURLRequest *) urlrequest;
-(IBAction)hideme;
@end



Best Answer-推荐答案


您的 View 元素仅在需要时才被实例化。这意味着对 Controller 的 view 属性的第一次引用(内部来自 UIKit 或代码中任何地方对“self.view”的引用)会触发实际创建你在你的 Nib 。

所以在上述过程发生之前,您的 webView 属性将为 nil。您很可能在实例化 View 之前调用了 loadRequest。您的问题的解决方案是在调用 loadRequest 时简单地更改。

那么调用 loadRequest 的正确时间是什么时候?有三种可能:

1) 如果您从 CustomWebView 内部调用 loadRequest,您可以将该代码放入 viewDidLoad

2) 如果您必须从 CustomWebView 外部调用 loadRequest,您可以等待您第一次展示该 Controller (例如使用 presentModalViewController:animated: 或将您的 Controller 推送到导航上stack) 然后调用 loadRequest。

所以你的代码可能看起来像:

NSURLRequest *someRequest = nil; //Assume this has some valid value

CustomWebView *myWebView = [[CustomWebView alloc] init]; //Plus other nib niceties
[self presentModalViewController:myWebView];
[myWebView loadRequest:someRequest];                     //View has been created, 
                                                         //loadRequest will work.

而不是原来的样子:

NSURLRequest *someRequest = nil; //Assume this has some valid value

CustomWebView *myWebView = [[CustomWebView alloc] init]; //Plus other nib niceties
[myWebView loadRequest:someRequest];                     //Your view is not created yet, loadRequest won't work.
[self presentModalViewController:myWebView];             

3) 如果您无法执行上述操作,并且无论您何时选择 presentModalViewControllerpushViewController,都必须能够在任何时间点调用 loadRequest,则永远是拯救世界的黑客

hack 是,只需引用 CustomWebView 的 init 方法中的 self.view,您就可以确信 View 已经在“init”之后设置好了。你如何引用 self.view 并不重要,即使像 [self.view setNeedsLayout] 这样的东西也可以。就像我说的,没关系。

这是一个相当简单的问题,但我想在这里列出所有选项,因为这是我过去常犯的一个相当常见的错误。

关于iphone - 为什么我的应用内浏览器没有加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6198778/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4