IOS "Wild path" get wkwebview content height do H5 native connection

Source: Internet
Author: User

Preface: Yes, it is. Just finished the last article has not slowed down the god, last article I also mentioned, want to talk with you about how the native +h5 seamless connection story. As a result, my friend sent me two pieces of his work. All the good articles are like this, so that you can have a new harvest every time you look at it. We are also committed to writing some articles that can help others solve the problem, and below I use another way to perfect the problem. After all, everyone is written according to UIWebView, I say the difference after the change of WK, theme ideas are different Oh ~
Plug two links, it's my friend's. You can also make a comparison

IOS "Ultimate Solution" for accurate webview content height, adaptive height
IOS "Kit Kat" get WebView content Height
IOS Wkwebview Pictures Click to enlarge and swipe left and right, similar/NetEase article features

First of all, let's talk about the application scenario, so you might be more receptive.

Example 1: A page is divided into two parts, the upper part is the article, the product picture and so on (H5) a web, the lower part is the native list (TableView)
So how to combine the H5 and the original, the simplest idea is to make the H5 into a table, right. Then the real height of the Web Part is the biggest difficulty pr.

Example 2: The above is a native introduction, the following is divided into 3 parts, which is part of the H5 page details, part of the comment list, part of the relevant recommendations and so on, so that the most reasonable structure is: the above as a Tabview table header, the following common with the same tabview, Embed the H5 Web into one tableviewcell. So the difficulty is how to get the Web this cell's height returns.

I'll take the second one for example. After all, the second is more complex, and example 1 many projects have been achieved, my friend's article can also achieve this function, the second example, I use Wkwebview to provide a new way of thinking.

The beep is so much, let's start with the point.

First of all to tell you, simple to get contentsize what (on the Internet a search everywhere of the several methods) I do not spit groove, their application is too limited, slightly in the rich text editing when the size of the image or some of the motion diagram will cause you to get the height is not allowed, Then the interface UI sucks.
Then the idea is still the same as my previous article using JS injection to solve
First from the time of loading
-(Instancetype) Initwithstyle: (Uitableviewcellstyle) style Reuseidentifier: (NSString *) reuseidentifier
{
self = [super Initwithstyle:style reuseidentifier:reuseidentifier];
if (self) {
Self.contentView.backgroundColor = Ninecolorone;
[Self creatsubviews];
}
return self;
}
-(void) creatsubviews
{
Wkwebviewconfiguration *CONFIFG = [[Wkwebviewconfiguration alloc] init];
confifg.selectiongranularity = Wkselectiongranularitycharacter;
_webview = [[Wkwebview alloc] Initwithframe:cgrectmake (0, CurrentScreenWidth-28, 1) CONFIGURATION:CONFIFG];
Self.contentView.backgroundColor = Ninecolorone;
_webview.scalespagetofit = NO;
_webview.scrollview.scrollenabled=no;
_webview.userinteractionenabled = NO;
_webview.opaque = NO;
_webview.scrollview.bounces=no;
_webview.backgroundcolor=ninecolorone;
_webview.scrollview.decelerationrate=uiscrollviewdecelerationratenormal;
[Self.contentview Addsubview:_webview];
}

I just said, put the web in a cell, then its agent will be in the VC to sign.
It is noted that _webview.scalespagetofit = no; This sentence I blocked, because Wkwebview is not this property of it and UIWebView different, but if not set no, The default effect of Wkwebview and Uiwebview.scalespagetofit = yes is the same, and you need this code at this time:

<meta content=\"width=device-width, initial-scale=1.0, maximum-scale=3.0, user-scalable=0;\" name=\"viewport\" />
    • 1

This piece of code is injected at the time of loading
For example:

- (void)setDetail:(NSString *)detail{        if(!_detail){                _detail = detail;            if (_detail.length >0) {                [_webView loadHTMLString:[NSString stringWithFormat:@"<meta content=\"width=device-width, initial-scale=1.0, maximum-scale=3.0, user-scalable=0;\" name=\"viewport\" />%@<div id=\"testDiv\" style = \"height:100px; width:100px\"></div>",_detail] baseURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]]]; } }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

Note 2 points:
1. Because the overall logic is that the web is placed in the cell, the load is completed after the refresh Tabview, then the time to refresh the proxy method Cellforrow, then the cell will be re-assigned to create a dead chain. So when it comes to assignment, do basic processing.
2. I injected the Scalespagetofit code at the same time, it seems to have added a div? Right, you're not mistaken. I'll tell you what this div is for.

We'll cut our sights back to VC

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath         _webview = cell.webView;        cell.webView.navigationDelegate = self; cell.webView.UIDelegate = self; cell.selectionStyle = 0; cell.detail = @"这里就是你要加载的html";
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

This is a partial code for the cell inside the proxy method. You can see the agent. We're all signed up for VC.
Look at the load completion method immediately

- (void) WebView: (Wkwebview *) WebView didfinishnavigation: (null_unspecified wknavigation *) navigation{[WebView evaluatejavascript:@id _nullable result,NSError * _nullable error) {//get page height and reset webview frame cgfloat lasth eight = [result doublevalue]; Webview.frame = CGRectMake (14, 0, Currentscreenwidth-28, lastheight); Webheight = Lastheight; [self.tableview beginupdates]; [self.tableview Endupdates];}];}     
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

Notice here, first of all, the JS injection method of wk change, and then you find that I take the web's height using the div block I just injected when I loaded the HTML
This way, no matter what your Web page is, add a div to the tail and its position is always the height you need. (Be sure to note that this code does not add the height of the same is not allowed to OH)

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    if(_type == 0){ return webHeight; }// 当前tableview是加载web状态时 cell返回高度
    • 1
    • 2
    • 3
    • 4
    • 5

At this time you will also find that when scrolling tableview, the content of the Web display does not change!!!
Yes, this is another difference between wkwebview, because Wkwebview uses the lazy load mode, where the ScrollView scroll is disabled, causing the nested wkcompositingview not to load the data.

-(void ) Scrollviewdidscroll: (uiscrollview *) ScrollView {// Determine if the cell webview is visible, if visible on layout nsarray *cells = self.tableview.visiblecells; for (uitableviewcell *cell in cells) { if ([cell Iskindofclass:[uitableviewcell class]]) {uitableviewcell *webcell = (uitableviewcell *) cell; [Webcell.webview Setneedslayout];} }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

You need to add this code.

Well, at this time, H5 is seamlessly connected with the original.
These things are not my own self-thought out, here also to my good friend-Xu Yang express my heartfelt thanks, is he gave me a lot of ideas. Yes, that's the person I recommended for the article above.

Still do not know what to write the next article, and recently suddenly to write a blog interest.

IOS "Wild path" get wkwebview content height do H5 native connection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.