最近一個(gè)小伙伴的公司業(yè)務(wù)邏輯上需要做在一個(gè)tableView的header上加載一個(gè)WebView的邏輯躁锁。我們?cè)?code>- (void)webViewDidFinishLoad:(UIWebView *)webView{ CGFloat heights = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"]floatValue]; NSLog(@"高度為:%f",heights); }中獲取的高度確是不正常的、是無(wú)法使用的萄喳。在查閱資料后得知在:web中有很多 圖片未加載完成 的話(huà),獲取的高度將小于真實(shí)高度种呐,那在它加載完成后拂蝎,內(nèi)容將顯示不全。我們必須換一種方式來(lái)獲取的網(wǎng)頁(yè)的真實(shí)高度霎迫。查閱后得知使用kvo能夠很好的解決的這個(gè)問(wèn)題≌啵現(xiàn)將代碼貼出以供后來(lái)者參考。當(dāng)然后有更好的方案可以再評(píng)論里提出知给,共同進(jìn)步一起提高瓤帚。
代碼示例:
#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