iOS-UIWebView加载html,文字大小颜色设置,图片自适应设置

来源:互联网 发布:c语言float是什么意思 编辑:程序博客网 时间:2024/06/06 06:44

UIWebView加载html,遇到了文字大小、颜色不符合要求的问题,而且图片也不能设置宽高。

经过多次尝试(UITextView代替尝试),终于有了解决方案:修改html源码,在其中加入font-size等的设置。

代码如下:代码思路是,把源代码中的所有font-size设置都删掉,然后把原html放在一个body里,再整体设置body的font-size等属性

//修改answer中的字号/边距/颜色,设置图片大小适应屏幕        NSString *answer = 你的html代码;        NSRange range = [answer rangeOfString:@"font-size:"];        if (range.location == NSNotFound) {            NSLog(@"can not change fontsize!");        } else {            NSArray*sourcearray = [answer componentsSeparatedByString:@"font-size:"];            NSMutableArray *bigArray = [NSMutableArray arrayWithArray:sourcearray];                        for (int i=1; i<bigArray.count; i++) {                NSArray *minArray = [bigArray[i] componentsSeparatedByString:@"px"];                if (minArray.count < 2) {                    minArray = [bigArray[i] componentsSeparatedByString:@"pt"];                }                if (minArray.count < 2) {                    minArray = [bigArray[i] componentsSeparatedByString:@"em"];                }                bigArray[i] = minArray[1];            }            answer = @"";            for (NSString *subStr in bigArray) {                answer = [answer stringByAppendingString:subStr];            }        }                //设置字体大小为14,颜色为0x666666,边距为18,并且图片的宽度自动充满屏幕,高度自适应        NSString *htmls = [NSString stringWithFormat:@"<html> \n"                           "<head> \n"                           "<style type=\"text/css\"> \n"                           "body {margin:18;font-size:14;color:0x666666}\n"                           "</style> \n"                           "</head> \n"                           "<body>"                           "<script type='text/javascript'>"                           "window.onload = function(){\n"                           "var $img = document.getElementsByTagName('img');\n"                           "for(var p in  $img){\n"                           " $img[p].style.width = '100%%';\n"                           "$img[p].style.height ='auto'\n"                           "}\n"                           "}"                           "</script>%@"                           "</body>"                           "</html>",answer];        self.htmlWebView.scalesPageToFit=YES;        [self.htmlWebView loadHTMLString:htmls baseURL:nil];
这样之后,就需要动态计算出UIWebView的高度,在webView的delegate里,计算高度,代码如下:

- (void)webViewDidFinishLoad:(UIWebView *)theWebView{    CGFloat scrollHeight = [[theWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];    [self.htmlWebView mas_updateConstraints:^(MASConstraintMaker *make) {        make.height.equalTo(@(scrollHeight));    }];}

即在加载完成之后,再计算真实高度。


0 0
原创粉丝点击