当前位置:首页 > 通信资讯 > 正文

最近项目中遇到在cell中获取webView的内容的尺寸的需求 实现的思路其实很简单 就是通过执行js 获取尺寸即可 为了后面用着方便我直接封装了一个HTML的cell 起名就叫

STHTMLBaseCell 下面是实现代码:

?
1 2 3 4 5 6 7 8 #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的内容的高度的

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 #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 //外界传入的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 的内容尺寸了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。