如何使用相同宽度的网页视图?

问题描述 投票:0回答:3

我想在Web视图中显示离线html。我希望Web视图高度与视图高度相同(它应该覆盖屏幕宽度)。它的高度与内容高度相同。我应该如何改变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];
}
ios objective-c webview
3个回答
1
投票

1-使用WKWebView作为UIWebView已弃用

2-

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

3-里面

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

1
投票

如果您的应用支持iOS 8+,请使用WKWebView而不是UIWebView,因为它已被弃用。

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

1
投票

是的,你应该使用@SH_Khan提到的WKWebView

如果您使用自动布局/约束,这是相同的Swift代码

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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.