最近项目中遇到在cell中获取webView的内容的尺寸的需求 实现的思路其实很简单 就是通过执行js 获取尺寸即可 为了后面用着方便我直接封装了一个HTML的cell 起名就叫
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
以上是.h文件的实现 很简单 就是声明了 STHTMLBaseCell 然后创建了代理 这个代理方法 就是返回给外部webView的内容的高度的
#import "STHTMLBaseCell.h"@interface STHTMLBaseCell()<UIWebViewDelegate>@property (weak, nonatomic) IBOutlet UIWebView *webView;@end@implementation STHTMLBaseCell- (void)awakeFromNib {[super awakeFromNib];// Initialization codeself.webView.scrollView.scrollEnabled = NO;self.webView.scrollView.pagingEnabled = NO;self.webView.delegate = self;self.webView.backgroundColor = [UIColor whiteColor];}- (void)configCellWithHtml:(NSString *)html //外界传入的html字符串{[self.webView loadHTMLString:html baseURL:nil];//加载html}#pragma mrak - UIWebViewDelegate- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect="auto";"];//让用户可以选中webview里面内容[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout="auto";"];//可以响应用户的手势NSURL *url = [request URL];if (![url host]) {return YES;} return NO;}- (void)webViewDidFinishLoad:(UIWebView *)webView{CGFloat height = [[webView stringByEvaluatingJavaScriptFromString: @"document.body.scrollHeight"] floatValue]; //获取webview内容的高度self.webView.height = height;if ([self.delegate respondsToSelector:@selector(webViewDidLoad:height:)]) {[self.delegate webViewDidLoad:self height:height];//调用代理的方法 }}@end
大致就这么简单 就能够在cell中获取webview 的内容尺寸了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。