获取Webview的高度
2016-12-25 本文已影响90人
小弱鸡
最近一个小伙伴的公司业务逻辑上需要做在一个tableView的header上加载一个WebView的逻辑。我们在- (void)webViewDidFinishLoad:(UIWebView *)webView{ CGFloat heights = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"]floatValue]; NSLog(@"高度为:%f",heights); }
中获取的高度确是不正常的、是无法使用的。在查阅资料后得知在:web中有很多 图片未加载完成 的话,获取的高度将小于真实高度,那在它加载完成后,内容将显示不全。我们必须换一种方式来获取的网页的真实高度。查阅后得知使用kvo能够很好的解决的这个问题。现将代码贴出以供后来者参考。当然后有更好的方案可以再评论里提出,共同进步一起提高。
代码示例:
#import "ViewController.h"
//#import "uiweb"
@interface ViewController ()<UIWebViewDelegate,UITableViewDelegate,UITableViewDataSource>{
CGFloat webViewHeight;
}
@property(nonatomic,strong)UIWebView * webView;
@property(nonatomic,strong)UITableView * listTab;
@end
@implementation ViewController
- (UIWebView *)webView{
if (!_webView) {
_webView = [[UIWebView alloc]initWithFrame:self.view.frame];
}
return _webView;
}
- (UITableView *)listTab{
if (!_listTab) {
_listTab = [[UITableView alloc]init];
}
return _listTab;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.listTab];
self.listTab.frame = self.view.bounds;
self.listTab.dataSource = self;
self.listTab.delegate = self;
[self.listTab registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ID"];
[self.view addSubview: self.webView];
NSURL *url = [NSURL URLWithString:@"http://118.178.152.151:8088/platform/news_detail.html?id=32"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
self.webView.delegate = self;
[self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
self.webView.scrollView.scrollEnabled = NO;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
cell.backgroundColor = [UIColor redColor];
return cell;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"contentSize"]) {
webViewHeight = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
CGRect newFrame = self.webView.frame;
newFrame.size.height = webViewHeight;
self.webView.frame = newFrame;
NSLog(@"%f",self.webView.frame.size.height);
[self.listTab setTableHeaderView:self.webView];
}
}
-(void)viewWillDisappear:(BOOL)antimated{
[super viewWillDisappear:antimated];
[self.webView.scrollView removeObserver:self
forKeyPath:@"contentSize" context:nil];
//也可以放在delloc方法中移除
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end