在iOS 8中,webView是零,但在使用xib的iOS 9中它并不是零

时间:2016-07-22 07:05:29

标签: ios webview

为什么webView在iOS 8中是零而在iOS 9中没有?

我应该如何在iOS 8中使用webview? 这是代码(swift 2.2)

viewController课程中:

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.webView?.delegate = self   // without '?' in iOS 8 crash
                                    // in iOS 9 not crash

    // debug code
    if let webView = self.webView { // iOS 8 nil
        print("\(webView)")         // iOS 9 not nil
    }

    //...
}

谢谢!

3 个答案:

答案 0 :(得分:0)

class ViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!

let url = NSURL(string: "http://google.com")


override func viewDidLoad() {
    super.viewDidLoad()

    self.webView.delegate = self

    let req = NSURLRequest(URL : url!)
    self.webView.loadRequest(req)
}

func webViewDidStartLoad(webView: UIWebView) {
    print("start loading")
}

func webViewDidFinishLoad(webView: UIWebView) {
    print("finish loading")
}

//...

}
像这样,这段代码可以在iOS8和iOS中完美运行。 iOS9

答案 1 :(得分:0)

一个解决方案:

@IBOutlet weak var webViewXib: UIWebView!
var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    if let _ = self.webViewXib {
    self.webView = self.webViewXib
    } else {
        self.webView = UIWebView()
        self.webView.frame = self.view.bounds
        self.view.addSubview(self.webView!)
    }
    self.webView!.delegate = self    

    // ...
}

答案 2 :(得分:0)

问题在于如何实例化View Controller,您可能将其实例化为:

MyViewController *myViewController = [[MyViewController alloc] init]

这样你就不会在viewDidLoad中准备好视图,而应该尝试:

MyViewController *myViewController = [[MyViewController alloc] initWithNibName:"MyViewController" bundle:nil]