在UIWebView中打开最后一个滚动位置

时间:2014-12-27 23:47:53

标签: ios swift uiwebview

我有一个WebView:

func loadPage() {
    let request = NSURLRequest (URL: url!)
    myBrowser.loadRequest(request)
}

从此网址加载RTF文档:

var url: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Chapter1", ofType: "rtf")!)!

如何将最后滚动位置保存到NSUserDefaults,然后获取它(如果用户暂停读取并恢复它)。

或者在这种情况下可能有其他类型或方法来制作书签。

注意:我一直在尝试这个:

var myBookmark: CGPoint = CGPointMake(0, 0)

override func viewWillDisappear(animated: Bool) {
myBookmark = myBrowser.scrollView.contentOffset
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)
    myBrowser.scrollView.delegate = self
    myBrowser.scrollView.setContentOffset(myBookmark, animated: false)
}

但它没有任何效果。

UPD1:翻译我的VAR名称。

1 个答案:

答案 0 :(得分:0)

要保存并检索NSUserDefaults的滚动浏览偏移量,请设置UIWebView代表并尝试此操作:

var viewLaidoutSubviews = false // <-- variable to prevent the viewDidLayoutSubviews code from happening more than once

// Save your content offset when the view disappears
override func viewWillDisappear(animated: Bool) {
    var userDefaults = NSUserDefaults.standardUserDefaults()
    userDefaults.setValue(NSStringFromCGPoint(myBrowser.scrollView.contentOffset), forKey: "scroll_offset")
    userDefaults.synchronize()

    viewLaidoutSubviews = false
}

// Retrieve and set your content offset when the view re-appears
// and its subviews are first laid out
override func viewDidLayoutSubviews() {

    if (!viewLaidoutSubviews) {
        // If a scroll_offset is store in NSUserDefaults, use it
        var userDefaults = NSUserDefaults.standardUserDefaults()
        var scrollOffset:CGPoint? = CGPointFromString(userDefaults.valueForKey("scroll_offset") as? NSString)
        if let position:CGPoint = scrollOffset {
            myBrowser.scrollView.delegate = self
            myBrowser.scrollView.setContentOffset(position, animated: false)
        }
        viewLaidoutSubviews = true
    }
}

利用UIWebView webViewDidFinishLoad委托方法更新滚动偏移,以便在视图布局其子视图之前网页视图未完成渲染:

// Retrieve and set your content offset once the web view has
// finished rendering (in case it hasn't finished rendering
// by the time the view's subviews were laid out)
func webViewDidFinishLoad(webView: UIWebView) {

    // If a scroll_offset is store in NSUserDefaults, use it
    var userDefaults = NSUserDefaults.standardUserDefaults()
    var scrollOffset:CGPoint? = CGPointFromString(userDefaults.valueForKey("scroll_offset") as? NSString)
    if let position:CGPoint = scrollOffset {
        myBrowser.scrollView.delegate = self
        myBrowser.scrollView.setContentOffset(position, animated: true)
    }
}

但请注意,除非您将其删除,否则您的NSUserDefaults值也会在应用启动之间保持不变。