How do I center the contents of a webview in iOS vertically and horizontally?

社会主义新天地 提交于 2020-01-13 13:29:29

问题


I have googled quite a bit and I can't seem to find anything that makes sense to me. I need to center the contents of a webview both vertically and horizontally. I have been able to get the horizontal to work with this:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *bodyStyle = @"document.getElementsByTagName('body')[0].style.textAlign = 'center';";
    [self.webView stringByEvaluatingJavaScriptFromString:bodyStyle];
}

But I can't find anything on vertical. Any ideas? Any help would be appreciated.


回答1:


Try like this,

NSString *bodyStyleVertical = @"document.getElementsByTagName('body')[0].style.verticalAlign = 'middle';";
NSString *bodyStyleHorizontal = @"document.getElementsByTagName('body')[0].style.textAlign = 'center';";
NSString *mapStyle = @"document.getElementById('mapid').style.margin = 'auto';";

[webView stringByEvaluatingJavaScriptFromString:bodyStyleVertical];
[webView stringByEvaluatingJavaScriptFromString:bodyStyleHorizontal];
[webView stringByEvaluatingJavaScriptFromString:mapStyle];

Hope it will helps you.....




回答2:


Keep everything in a table and then align the table cells.

CSS

td {
    text-align: center;
    vertical-align: middle;
}

or

<table border="1">
    <tr>
        <td align="center" valign="middle">Text</td>
        <td align="center" valign="middle">Text</td>
    </tr>
</table>



回答3:


Vertical centering:

CGSize contentSize = webView.scrollView.contentSize;
CGFloat d = contentSize.height/2 - webView.center.y;
[webView.scrollView setContentOffset:CGPointMake(0, d) animated:NO];


来源:https://stackoverflow.com/questions/16741558/how-do-i-center-the-contents-of-a-webview-in-ios-vertically-and-horizontally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!