【问题标题】:Webview autoheight to content is not working on iOS (Appcelerator Titanium)Webview 对内容的自动高度在 iOS 上不起作用(Appcelerator Titanium)
【发布时间】:2016-11-29 04:36:19
【问题描述】:

我想添加高度为内容的 webview。我让它在 Android 上运行顺畅,但在 iOS 上,文本越长,文本下方的空间就越长。

这是我的代码:

var window = Ti.UI.createWindow();

var scrollView = Ti.UI.createScrollView({
    layout: 'vertical',
    height: Ti.UI.SIZE
});

    var view1 = Ti.UI.createView({
        height: 200,
        backgroundColor: 'red'
    });

    var webview = Ti.UI.createWebView({
        height: Ti.UI.SIZE,     
        html: '<html><head><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2"></head><body style="margin:0; background-color: blue">Some page some text2</body></html>'
    });

    var view2 = Ti.UI.createView({
        height: 200,
        backgroundColor: 'green'
    });

    scrollView.add(view1);
    scrollView.add(webview);
    scrollView.add(view2);

    window.add(scrollView);

window.open();

提前致谢。

【问题讨论】:

    标签: webview titanium appcelerator titanium-mobile appcelerator-mobile


    【解决方案1】:

    webview 不知道内容的大小。但是你可以问 webview 内容有多高。​​

    为此,您需要使用evalJS

    使用StackOverflow上的JS:

    var body = document.body,
        html = document.documentElement;
    
    var height = Math.max( body.scrollHeight, body.offsetHeight, 
                           html.clientHeight, html.scrollHeight, html.offsetHeight );
    

    最好把它放在 webview 中的一个函数中。假设上面的 Javascript 在函数 getDocumentHeight 中,并且该函数返回 height 属性。现在,要获得高度,请像这样使用 eval:

    var height = webview.evalJS('getDocumentHeight()');
    webview.height = height;
    

    现在,您希望每次加载内容时都执行此操作,假设内容发生变化,因此在这种情况下,您可以观看 load 事件 (doc here) 并在每次此事件时触发上面的 evalJS被解雇了。

    它不会很漂亮,因为 webview 不打算像这样缩放,但它可以工作。

    【讨论】:

    • 同意这不是很漂亮,但我发现使它工作的唯一方法。而且我已经尝试了多年!
    • 此方法给出与 Ti.UI.SIZE 相同的高度。例如文本:'Some page some text2 Some page some text2 Some page some text2'将返回高度:240(在Android上它是38,这是正确的值)所以下面仍然有差距。请尝试代码。
    • 奇怪的是,高度并没有随着线函数的增加而增加。例如:如果在 iOS 上为 240,则实际高度为 38(~6.31x),如果为 7060,则实际高度为 931(~7.58x)。所有 iOS 设备(iPhone 5/6、iPad Pro)的值都相同,这也令人惊讶(Iphone 5 上的差距比 iPad Pro 上的小)。
    • 在 iOS 上,返回的高度似乎与字符数有关。如果在 Android 上我们有 4 行文本(高度:76),那么在 iOS 上(取决于字符数量)我们将有如下值:560、640、720、800。但是对于 5 行文本(高度:Android 上的 96 ) 我们将从 iOS 上的 ~880 开始。
    【解决方案2】:

    这似乎是 iOS 的一个错误/不鼓励的方法。没有直接的解决方法。可以在这里检查: Jira Ticket about problem with iOS 9, Jira Ticket about problem with webView + ScrollView

    【讨论】:

      猜你喜欢
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多