UIWebView使用時當無法確切的設置一個固定的高度時,就需要根據網頁內容來自適應高度了,參考代碼如下:
//
// ViewController.m
// UIwebView高度自適應
//
// Created by mac on 16/3/18.
// Copyright © 2016年 ZMIT. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<UIScrollViewDelegate,UIWebViewDelegate>{
UIWebView *myWebView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor grayColor];
myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 30)];
myWebView.delegate = self;
myWebView.scrollView.delegate = self;
myWebView.scalesPageToFit = YES;//自動對頁面進行縮放以適應屏幕
[self.view addSubview:myWebView];
NSURL *url = [NSURL URLWithString:@"http://www.111cn.net/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[myWebView loadRequest:request];
}
#pragma mark - 代理方法
-(void)webViewDidFinishLoad:(UIWebView *)webView{
CGFloat webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"]floatValue];
CGRect newFrame = webView.frame;
newFrame.size.height = webViewHeight;
webView.frame = newFrame;
//重新設置webView的contentSize
myWebView.scrollView.contentSize = newFrame.size;
//如果WebView塊下面還有其他的控件,可在此處根據myWebView設置其frame
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end