iOS gets the content size of webview in cell

  • 2020-12-09 01:03:41
  • OfStack

In a recent project, I came across the need to obtain the size of webView's content in cell. The idea of achieving the size is actually very simple, which is to perform js to obtain the size for convenience. I directly encapsulated 1 HTML in cell and named it cell

Here is the implementation code for STHTMLBaseCell:


#import "STBaseTableViewCell.h"@class STHTMLBaseCell;
@protocol STHtmlBaseDelegate <NSObject>
- (void)webViewDidLoad:(STHTMLBaseCell *)cell height:(CGFloat)height;
@end
@interface STHTMLBaseCell : STBaseTableViewCell
@property (weak, nonatomic) id<STHtmlBaseDelegate>delegate;

@end

So that's the implementation of the.h file which is simply declaring STHTMLBaseCell and then creating a proxy and that proxy method is the height of the content returned to the external webView


#import "STHTMLBaseCell.h"

@interface STHTMLBaseCell()<UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;@end

@implementation STHTMLBaseCell

- (void)awakeFromNib {
  [super awakeFromNib];
  // Initialization code
  self.webView.scrollView.scrollEnabled = NO;
  self.webView.scrollView.pagingEnabled = NO;
  self.webView.delegate = self;
  self.webView.backgroundColor = [UIColor whiteColor];
}
- (void)configCellWithHtml:(NSString *)html // Exogenous html string 
{
  [self.webView loadHTMLString:html baseURL:nil];// loading html
}

#pragma mrak - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  
  [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='auto';"];// Allows the user to select webview The content inside 
  [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='auto';"];// Can respond to user gestures 
  
  NSURL *url = [request URL];
  if (![url host]) {
    return YES;
  }
 return NO;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
  CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:
             @"document.body.scrollHeight"] floatValue]; // To obtain webview Height of content 
  self.webView.height = height;
  if ([self.delegate respondsToSelector:@selector(webViewDidLoad:height:)]) {
    [self.delegate webViewDidLoad:self height:height];// Method to invoke the proxy  
  }
}


@end

This is about as simple as getting the content size of webview in cell.


Related articles: