首页 > 代码库 > UIWebView中加载HTML的Table,td设置百分比宽度并且宽度不被里面的内容撑开

UIWebView中加载HTML的Table,td设置百分比宽度并且宽度不被里面的内容撑开

正常情况下,iOS使用WebView加载HTML的Table时,为了让Table适应屏幕宽度,会使用百分比设置td的宽度,但是由于td中的内容过多,td会被撑开,导致整个Table的宽度会变宽,超出屏幕的宽度。

普通情况下可以设置scalesPageToFit=YES并且td的宽度按百分比设置下就行。实例如下:

1.创建WebView

{//创建WebView
        CGFloat webX = 0;
        CGFloat webY = offset_y;
        CGFloat webW = kAllWidth;
        CGFloat webH = kAllHeight - webY;
        
        self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(webX, webY, webW, webH)];
        self.webView.opaque = NO;
        self.webView.backgroundColor = [UIColor whiteColor];
        self.webView.scalesPageToFit = YES;
        self.webView.delegate = self;
        self.webView.tag = webViewTag + 2;
        [vContainer addSubview:self.webView];
}

2.加载HTML

- (void)loadWebData{
    
    NSString *urlText = [self createURLString];
    [self.webView loadHTMLString:urlText baseURL:nil];
    
}

- (NSString *)createURLString{
    
    NSMutableString *urlString = [[NSMutableString alloc] initWithString:@"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"];
    [urlString appendString:@"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"];
    [urlString appendString:@"<head>\n"];
    [urlString appendString:@"<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n"];
    
    [urlString appendString:@"<style type=\"text/css\">\n\
     *{margin:0;padding:0;}\n     table{cellSpacing:0;cellPadding:0;border-collapse:collapse;}\n     table th,table td{ border:1px solid #ccc;align:center;text-align:center;}\n     .table-head{background-color:#d31145;color:#fff;}\n     .table-body{width:100%;height:100%;}\n     .table-head table,.table-body table{width:100%;}\n     .table-body table tr:nth-child(2n+1){background-color:#e2e2e2;}\n     </style>\n"];
    
    [urlString appendString:@"</head>\n"];
    [urlString appendString:@"<title></title>\n"];
    [urlString appendString:@"<body style=\"width:100%\" width=\"100%\" height=\"100%\">\n"];
    
    if (self.dataSource.count!=0) {
        //[urlString appendString:@"<div class=\"table-body\">\n"];
        [urlString appendString:@"<table class=\"table-body\" id=\"content_table\" style=\"width:100%;\" cellSpacing=\"0px\";cellPadding=\"0px\";>\n"];
        //初始化表格的行
        for (int i=0; i<self.dataSource.count; i++) {
            [urlString appendString:@"<tr style=\"font-size:22px;\" onclick=\"clickRow(this);\">\n"];
            ThSalesOrderModel *model = [self.dataSource objectAtIndex:i];
            
            for (int i=0; i<6; i++) {
                if (i == 0) {
                    [urlString appendString:[NSString stringWithFormat:@"<td width=\"25%%\" style=\"padding:5px\">%@</td>\n",model.OrderDate]];
                }
                if (i == 1) {
                    [urlString appendString:[NSString stringWithFormat:@"<td width=\"25%%\" style=\"padding:5px\">%@</td>\n",model.deliverdate]];
                }
                if (i == 2) {
                    [urlString appendString:[NSString stringWithFormat:@"<td width=\"16.6%%\" style=\"padding:5px\">%@</td>\n",model.CustomerName]];
                }
                if (i == 3) {
                    [urlString appendString:[NSString stringWithFormat:@"<td width=\"16.6%%\" style=\"padding:5px\">%@</td>\n",model.SalesOrder]];
                }
                if (i == 4) {
                    [urlString appendString:[NSString stringWithFormat:@"<td width=\"16.6%%\" style=\"padding:5px\">%@</td>\n",model.Status]];
                }
                
                //actualCaseCount += [model.actqty doubleValue];
                //targetCaseCount += [model.target doubleValue];
            }
            [urlString appendString:@"</tr>\n"];
        }
        [urlString appendString:@"</table>\n"];
        [urlString appendString:@"</div>\n"];
    }else{
        [urlString appendString:@"<div\">\n"];
        [urlString  appendFormat:@"<span style=\"font-size:25px;display:block;text-align:center;margin-top:40px;color:#bbb;\">%@</sapn>",kTXT(@"NoData")];
        //[urlString appendString:@"</div>\n"];
    }
    
    
    [urlString appendString:@"</body>\n"];
    [urlString appendString:@"</html>\n"];
    [urlString appendString:@"     <script type=\"text/javascript\">\n\
     function clickRow (obj) {\n         var salesOrder = obj.childNodes[7].innerText;\n         var msg = \"push://\"+salesOrder;\n\
         //alert(msg);\n\
         loadURL(msg);\n     }\n     function loadURL (url) {\n         var iFrame;\n         iFrame = document.createElement(\"iFrame\");\n\
         iFrame.setAttribute(\"src\",url);\n\
         iFrame.setAttribute(\"style\",\"display:none\");\n\
         iFrame.setAttribute(\"height\",\"0px\");\n\
         iFrame.setAttribute(\"width\",\"0px\");\n\
         iFrame.setAttribute(\"frameborder\",\"0\");\n\
         document.body.appendChild(iFrame);\n         //移除iFrame\n\
         iFrame.parentNode.removeChild(iFrame);\n         iFrame = null;\n     }\n     </script>\n     "];
    NSLog(@"生成的HTML字符串是:%@",urlString);
    
    return urlString;
}

3.效果截图。(下图中的表格头部和表格内容是两个WebView分别加载两个HTML,然后相同列的比例设置相同就可以对齐了。同时表格内容向上滚动的时候,表头不会消失,类似于TableView的Header悬停效果)

技术分享

 

但是以上方法并不适用于所有的情况,当td中的内容太多的时候,表格就会乱掉。

技术分享

这个表格和上面的表格的构造基本相同,表头和内容分别使用两个WebView进行加载两个HTML的Table,然后td的宽度设置成百分比,结果并不像我们想的那样美好,表格的内容错乱了。。。

经过仔细的思考,我认为是泰国人的名字太长,换行的方式是按整个单词换行,我们可以修改下换行的方式。修改后的代码:(修改的部分我加了深灰的背景)

- (void)loadWebData{
    [SVProgressHUD showWithStatus:kTXT(@"IMLoading")];
    NSString *urlText = [self createURLString];
    [self.webView loadHTMLString:urlText baseURL:nil];
    //刷新底部的Table
    //[self loadBottomData];
    
}

- (NSString *)createURLString{
    
    NSMutableString *urlString = [[NSMutableString alloc] initWithString:@"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"];
    [urlString appendString:@"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"];
    [urlString appendString:@"<head>\n"];
    [urlString appendString:@"<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n"];
    /*
     [urlString appendString:@"<style type=\"text/css\">     *{margin:0;padding:0;}     table{cellSpacing:0;cellPadding:0;border-collapse:collapse;}     table th,table td{ border:1px solid #ccc;align:center;text-align:center;}     .table-head{background-color:#d31145;color:#fff;}     .table-body{width:100%;height:1200px;overflow-y:scroll;}     .table-head table,.table-body table{width:100%;}     .table-body table tr:nth-child(2n+1){background-color:#e2e2e2;}     </style>"];
     */
    
    //if (kGlobal.isIPhone6) {
        [urlString appendString:@"<style type=\"text/css\">\n\
         *{margin:0;padding:0;}\n         table{cellSpacing:0;cellPadding:0;border-collapse:collapse;}\n         table th,table td{ border:1px solid #ccc;align:center;text-align:center;}\n         .table-head{background-color:#d31145;color:#fff;}\n         .table-body{width:100%;height:100%;overflow-y:scroll;}\n         .table-head table,.table-body table{width:100%;}\n         .table-body table tr:nth-child(2n+1){background-color:#e2e2e2;}\n         </style>\n"];
    
    [urlString appendString:@"</head>\n"];
    [urlString appendString:@"<title></title>\n"];
    [urlString appendString:@"<body style=\"width:100%;max-width:100%;overflow:hidden;\" width=\"100%\" height=\"100%\">\n"];
    
    if (self.targetDataSource.count!=0) {
        [urlString appendString:@"<table style=\"width:100%;max-width:100%;table-layout:fixed;word-break:break-all;\" cellSpacing=\"0px\";cellPadding=\"0px\";>\n"];
        
        self.actualCaseCount = 0;
        self.targetCaseCount = 0;
        
        
        //初始化表格的行
        for (int j=0; j<self.targetDataSource.count; j++) {
            [urlString appendString:@"<tr style=\"font-size:22px;width:100%;\">\n"];
            ThCustomerTargetModel *model = [self.targetDataSource objectAtIndex:j];
            
            for (int i=0; i<6; i++) {
                if (i == 0) {
                    [urlString appendString:[NSString stringWithFormat:@"<td width=\"20%%\" style=\"padding:5px\">%@(%@)</td>\n",model.CustomerName,model.CustomerID]];
                }
                if (i == 1) {
                    [urlString appendString:[NSString stringWithFormat:@"<td width=\"20%%\" style=\"\">%@</td>\n",model.YearAndMonth]];
                }
                if (i == 2) {
                    [urlString appendString:[NSString stringWithFormat:@"<td width=\"20%%\" style=\"\">%@</td>\n",model.LastYearActualCase]];
                }
                if (i == 3) {
                    [urlString appendString:[NSString stringWithFormat:@"<td width=\"20%%\" style=\"padding:0px;font-size:22px;\" onclick=\"textOutClick(this);\"><input type=\"text\" style=\"padding:0px;margin:0px;width:95%%;height:60px;font-size:22px;\" onclick=\"textOnFocus(this)\" value=http://www.mamicode.com/"%@\" /></td>\n",model.ThisYearTargetCase]];
                }
                if (i == 4) {
                    //if ([model.ThisYearTargetCase isEqualToString:@""]||(model.ThisYearTargetCase == nil)) {
                        [urlString appendString:@"<td width=\"20%\" name=\"checkCell\" style=\"font-size:22px;\" onclick=\"checkOneCell(this);\"><input type=\"checkbox\" onclick=\"checkOneBox(this);\"></td>\n"];
                    //}
                }
            }
            [urlString appendString:@"</tr>\n"];
        }
        
        [urlString appendString:@"</table>\n"];
    }else{
        self.actualCaseCount = 0;
        self.targetCaseCount = 0;
        
        [urlString  appendFormat:@"<span style=\"font-size:25px;display:block;text-align:center;margin-top:40px;color:#bbb;\">%@</sapn>",kTXT(@"NoData")];
    }
    
    [urlString appendString:@"</body>\n"];
    [urlString appendString:@"</html>\n"];
    [urlString appendFormat:@"<script type=\"text/javascript\">"];
    [urlString appendFormat:@"\n     function selectedAll(){\n         var items = document.getElementsByName(\"checkCell\");\n\
         for (var i = 0; i < items.length; i++) {\n             items[i].firstChild.checked = true;\n         }\n     }\n     function deselectedAll(){\n         var items = document.getElementsByName(\"checkCell\");\n\
         for (var i = 0; i < items.length; i++) {\n             items[i].firstChild.checked = false;\n         }\n     }\n     //选中一个td,弹出的信息提示格式:row_index_Selected\n\
     function checkOneCell(obj){\n         var totalCheckbox = obj.firstChild;\n         var msg = \"thpush://row_\";\n\
         if (totalCheckbox.checked) {\n             totalCheckbox.checked = false;\n             msg += obj.parentNode.rowIndex+\"_0\";\n\
         }else{\n             totalCheckbox.checked = true;\n             msg += obj.parentNode.rowIndex+\"_1\";\n\
         }\n         //alert(msg);\n\
         loadURL(msg);\n     }\n     function checkOneBox(e){\n         var superNode = e.parentNode;\n         if (e.checked == true) {\n             e.checked = false;\n         }else{\n             e.checked = true;\n         }\n         var e = window.event || e;\n         e.cancelBubble = true;\n         //手动传播事件\n\
         checkOneCell(superNode);\n     }\n     function loadURL (url) {\n         var iFrame;\n         iFrame = document.createElement(\"iFrame\");\n\
         iFrame.setAttribute(\"src\",url);\n\
         iFrame.setAttribute(\"style\",\"display:none\");\n\
         iFrame.setAttribute(\"height\",\"0px\");\n\
         iFrame.setAttribute(\"width\",\"0px\");\n\
         iFrame.setAttribute(\"frameborder\",\"0\");\n\
         document.body.appendChild(iFrame);\n         //移除iFrame\n\
         iFrame.parentNode.removeChild(iFrame);\n         iFrame = null;\n     }\n     //点击<td>触发的方法\n\
     function textOutClick(obj){\n         //获得里面text的值\n\
         var text = obj.childNodes[0].value;\n         var msg = \"thpushone://\";\n\
         msg += \"text_\"+text+\"_row_\"+obj.parentNode.rowIndex;\n\
         //alert(msg);\n\
         loadURL(msg);\n     }\n     //点击<text>触发的方法\n\
     function textOnFocus(obj){\n         var superNode = obj.parentNode;\n         var e = window.event || obj;\n         e.cancelBubble = true;\n         //手动传播事件\n\
         textOutClick(superNode);\n     }\n    "];
    
    [urlString appendFormat:@"</script>"];
    
    
    //NSLog(@"生成的HTML字符串是:%@",urlString);
    
    return urlString;
}

最后显示的结果如下:

技术分享

 

最后注明一个小知识:

如何设置WebView的高度,让WebView适应加载内容的高度,达到加载内容多高,WebView就是多高的一个效果?

方法是:在WebView的webViewDidFinishLoad代理方法中去设置WebView的高度。

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    NSUInteger tag = webView.tag - webViewTag;
    
    if (tag == 1) {
        CGRect frame = webView.frame;
        frame.size.width = kAllWidth;
        frame.size.height = 1;
        webView.frame = frame;
        frame.size.height = webView.scrollView.contentSize.height;
        webView.frame = frame;
        webView.scrollView.scrollEnabled = NO;
    }
}

 

 

 

<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #703daa } span.s1 { }</style>

UIWebView中加载HTML的Table,td设置百分比宽度并且宽度不被里面的内容撑开