ios - WKWebView 添加为 Subview 不会在 Swift 中旋转时调整大小

标签 ios swift rotation addsubview wkwebview

我正在努力为我的浏览器应用程序添加一个新的阅读 View 。它是另一个 View Controller ,仅包含一个 WKWebView 添加为带有按钮(和手势)以关闭 View 的 subview 。一切正常,但是当我旋转设备时, subview 没有调整大小,所以我有一半的屏幕是空的。

阅读 View 中的 WKWebView 获取主视图 Controller 的 URL,并在用户点击主视图 Controller 上的按钮后执行 segue,该 URL 存储为 webpageURL。

这是我使用的代码:

import UIKit
import WebKit

class ReadingViewController: UIViewController, UIGestureRecognizerDelegate, WKNavigationDelegate, WKScriptMessageHandler {

@IBOutlet weak var _closeButton: UIButton!
@IBOutlet weak var _progressView: UIProgressView!
@IBOutlet weak var _loadingErrorView: UIView!

var webpageURL: NSURL?

var _webView: WKWebView?
var _isMainFrameNavigationAction: Bool?
var _loadingTimer: NSTimer?

var _swipeFromTopRecognizer: UIScreenEdgePanGestureRecognizer?
var _panFromRightRecognizer: UIScreenEdgePanGestureRecognizer?
var _panFromLeftRecognizer: UIScreenEdgePanGestureRecognizer?
var _errorView: UIView?
var _isCurrentPageLoaded = false

var _progressTimer: NSTimer?
var _isWebViewLoading = false


override func viewDidLoad() {
    super.viewDidLoad()

    var contentController = WKUserContentController();
    var scaleToFit = WKUserScript(source: "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);", injectionTime: WKUserScriptInjectionTime.AtDocumentStart, forMainFrameOnly: true)
    contentController.addUserScript(scaleToFit)
    contentController.addScriptMessageHandler(self, name: "callbackHandler")

    var webViewConfiguration: WKWebViewConfiguration = WKWebViewConfiguration()
    webViewConfiguration.allowsInlineMediaPlayback = true
    webViewConfiguration.mediaPlaybackRequiresUserAction = false

    _webView = WKWebView(frame: self.view.frame, configuration: webViewConfiguration)

    self.view.addSubview(_webView!)
    _webView!.navigationDelegate = self
    self.view.sendSubviewToBack(_webView!)
    _webView!.allowsBackForwardNavigationGestures = true

    _loadingErrorView.hidden = true

    _swipeFromTopRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("handleSwipeFromTop:"))
    _swipeFromTopRecognizer!.edges = UIRectEdge.Top
    _swipeFromTopRecognizer!.delegate = self
    self.view.addGestureRecognizer(_swipeFromTopRecognizer!)

    _progressView.hidden = true

    var urlAsString = "\(webpageURL!)"
    loadURL(urlAsString)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// UI Control Functions

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

@IBAction func closeReadingView(sender: AnyObject) {
    self.dismissViewControllerAnimated(true, completion: nil)
}

func closeButtonEnabled(bool:Bool) {
    _closeButton.enabled = bool
}

func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
    if(message.name == "callbackHandler") {
        println("JavaScript is sending a message \(message.body)")
    }
}


// WebView Functions

func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    _loadingErrorView.hidden = true
    _isWebViewLoading = true
    _progressView.hidden = false
    _progressView.progress = 0
    _progressTimer = NSTimer.scheduledTimerWithTimeInterval(0.01667, target: self, selector: "progressTimerCallback", userInfo: nil, repeats: true)
    _loadingTimer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: "loadingTimeoutCallback", userInfo: nil, repeats: false)
}

func loadingTimeoutCallback() {
    _webView?.stopLoading()
    handleWebViewError()
}

func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
    _isCurrentPageLoaded = true
    _loadingTimer!.invalidate()
    _isWebViewLoading = false

    if self._webView!.URL == webpageURL! {
        handleWebViewError()
        println(webpageURL!)
        println(self._webView!.URL!)
    } else {
        println("Page was loaded successfully")
        println(webpageURL!)
        println(self._webView!.URL!)
    }
}

func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
    _isCurrentPageLoaded = true
    _loadingTimer!.invalidate()
    _isWebViewLoading = false
}

func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
    if let newFrameLoading = _isMainFrameNavigationAction {
        } else {
        handleWebViewError()
    }
}

func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
    if let newFrameLoading = _isMainFrameNavigationAction {
        } else {
        handleWebViewError()
    }
}

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
    if (navigationAction.targetFrame == nil && navigationAction.navigationType == .LinkActivated) {
        _webView!.loadRequest(navigationAction.request)
    }
    _isMainFrameNavigationAction = navigationAction.targetFrame?.mainFrame
    decisionHandler(.Allow)
}

func handleWebViewError() {
    _loadingTimer!.invalidate()
    _isCurrentPageLoaded = false
    _isWebViewLoading = false
    displayLoadingErrorMessage()
}

func progressTimerCallback() {
    if (!_isWebViewLoading) {
        if (_progressView.progress >= 1) {
            _progressView.hidden = true
            _progressTimer?.invalidate()
        } else {
            _progressView.progress += 0.2
        }
    } else {
        _progressView.progress += 0.003
        if (_progressView.progress >= 0.95) {
            _progressView.progress = 0.95
        }
    }
}

func loadURL(urlString: String) {
    let addrStr = httpifyString(urlString)
    let readingAddr = addrStr.stringByAddingPercentEncodingForFormUrlencoded()!
    let addr = NSURL(string: "http://mobilizer.instapaper.com/m?u=\(readingAddr)")
    if let webAddr = addr {
        let req = NSURLRequest(URL: webAddr)
        _webView!.loadRequest(req)
    } else {
        displayLoadingErrorMessage()
    }

}

func httpifyString(str: String) -> String {
    let lcStr:String = (str as NSString).lowercaseString
    if (count(lcStr) >= 7) {
        if (lcStr.rangeOfString("http://") != nil) {
            return str
        } else if (lcStr.rangeOfString("https://") != nil) {
            return str
        }
    }
    return "http://"+str
}


func displayLoadingErrorMessage() {
    _loadingErrorView.hidden = false
}

func handleGoBackPan(sender: UIScreenEdgePanGestureRecognizer) {
    if (sender.state == .Ended) {
            _webView!.goBack()
    }
}

func handleGoForwardPan(sender: AnyObject) {
    if (sender.state == .Ended) {
            _webView!.goForward()
    }
}

func handleSwipeFromTop(sender: AnyObject) {
    self.dismissViewControllerAnimated(true, completion: nil)
}

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animateAlongsideTransition({ context in
        self._webView!.frame = CGRectMake(0, 0, size.width, size.height)
    }, completion: nil)
}

下面是一些截图来演示这个问题: 这是加载完成后的 View ,工作正常: This is how the view loads, working correctly

这是将设备旋转到横向后的 View : This is the view after rotation

这是旋转后的滚动位置: Scroll location after rotation

使用 self.view = _webView 可以使 View 正确调整大小,但会忽略 Storyboard 上的所有 View (因为 View 的内容正在被重写)。

如何解决这个问题(不重写 self.view)?

最佳答案

我设法通过使用这行代码解决了这个问题:

self._webView!.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight

:)

关于ios - WKWebView 添加为 Subview 不会在 Swift 中旋转时调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30737254/

相关文章:

ios - 如何在 Swift 中的 View Controller 和其他对象之间共享数据?

ios - UITextView 偏移文本的方式与 UILabel 不同

c++ - 从OpenCV中的旋转图像旋转回点

objective-c - 如何在旋转的 UIView 中使用 CGRectContainsPoint()

iphone - MPMoviePlayer 完成按钮问题

iphone - UIScrollView 未使用 setContentOffset 滚动到正确位置 :animated:

ios - 单元格变量为零,其中设置了值 collectionview 索引路径

ios - `rightBarButtonItem` 没有垂直对齐

Swift 子模块——它们到底是什么

Android配置已更改