How to share a single Web view on multiple view controllers

Asked 2 years ago, Updated 2 years ago, 47 views

The app I make is based on the Tabbar controller, and I want to make 3 tabs share one web view. When you tap the second and third tabs, you load different pages into the same web view. I don't know how to organize it. Help me

ios objective-c swift

2022-09-22 11:33

1 Answers

1. Create a web view with a single tone

class WebView: UIWebView
{
    static let sharedInstance = WebView()
}

2.Add this web view to the view controller of the tab.

import UIKit

class FirstViewController: UIViewController {

    override func viewWillAppear(animated: Bool)
    {
        let url = NSURL (string: "http://hashcode.co.kr")
        let requestObj = NSURLRequest(URL: url!)
        WebView.sharedInstance.loadRequest(requestObj)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(WebView.sharedInstance)
        WebView.sharedInstance.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
    }

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


}

You can now add a web view to all three tabs in the same way and load different pages from viewDidLoad.

But I don't know if it's going to be efficient. You have to load a new page over the network every time. If you just write three different web views, each web view has a loaded page, so you don't have to load the page over the network every time, right? Is there any special reason why you want to use the same web view on three tabs?


2022-09-22 11:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.