Fattaneh Talebi
Fattaneh Talebi

Reputation: 777

How to have a web view with the same width of screen?

I want to show a offline html in a web view. I want the web view height be the same as view height(It should cover the how screen width). And its height be the same as content height. How should I change initWithFrame?

- (void)viewDidLoad {
    [super viewDidLoad];

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)];

    NSString *htmlTxt = [[NSUserDefaults standardUserDefaults]
                                      stringForKey:@"HTML"];
    [webView loadHTMLString: htmlTxt baseURL:nil];
    [self.view addSubview:webView];
}

Upvotes: 1

Views: 1026

Answers (3)

Shehata Gamal
Shehata Gamal

Reputation: 100549

1- Use WKWebView as UIWebView is deprecated

2-

UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.frame];

3- Inside

- (void)webViewDidFinishLoad:(UIWebView *)webView {
  webview.frame = CGRectMake(0.0, 0.0,self.view.frame.size.width,webview.contentSize.height);
}

Upvotes: 2

Satish
Satish

Reputation: 2043

Yes, you should use WKWebView as mentioned by @SH_Khan

Here is the Swift code for the same if you are using auto layout/constraints

import WebKit

override func viewDidLoad() {
    super.viewDidLoad()
    //let webView = UIWebView(frame: CGRect.zero)
    let webView = WKWebView(frame: CGRect.zero)

    webView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(webView)
    view.bringSubviewToFront(webView)

    webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    webView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    if let htmlTxt = UserDefaults.standard.string(forKey: "HTML") {
        webView.loadHTMLString(htmlTxt, baseURL: nil)
    }
}

Upvotes: 1

Lal Krishna
Lal Krishna

Reputation: 16200

If your app supports iOS 8+, use WKWebView instead of UIWebView since its deprecated.

WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
webView.navigationDelegate = self;

Upvotes: 1

Related Questions