webView基本用法

  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     // Do any additional setup after loading the view, typically from a nib.  
  5.     UIWebView *webView = [[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)] autorelease];  
  6.       
  7.     //使用loadHTMLString()方法显示网页内容  使用此方法是如果html非完整需要进行转换!!
  8.     [webView loadHTMLString:[self getHtmlString] baseURL:nil];  
  9.   
  10.     [self.view addSubview:webView];  
  11. }  
  12.     //读取html文件内容  
  13. - (NSString *)getHtmlString{  
  14.     //文件路径  
  15.     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];  
  16.       
  17.     NSString *contents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];  
  18.     return contents;  
  19. }  

1. 给他设置一个代理类  UIWebView needs a delegate to reset it's size accoreding to it's content.
2. 代理类中实现如下方法 Implish "- (void)webViewDidFinishLoad:(UIWebView *) webView" in the delegate:

- (void)webViewDidFinishLoad:(UIWebView *) webView
{
    CGSize actualSize = [webView sizeThatFits:CGSizeZero];

    CGRect newFrame = webView.frame;
    newFrame.size.height = actualSize.height;
    webView.frame = newFrame;
}

3. OK.

二.使用javascipt获得可是可视区域宽高

@implementation UIWebView (SFHFStringMetrics)

- (CGSize) sizeOfDocument {

NSString *javascriptString = @"\"{\" + document.documentElement.clientWidth + \", \" + document.documentElement.clientHeight + \"}\"";

NSString *sizeString = [self stringByEvaluatingJavaScriptFromString: javascriptString];

if (!sizeString || [sizeString length] < 1) {

returnCGSizeZero;

}

returnCGSizeFromString(sizeString);

}

5.禁止长按事件

[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];

[webView stringByEvaluatingJavaScriptFromString:@"document.body.style.webkitTouchCallout='none';"];

原文地址:https://www.cnblogs.com/Cristen/p/3064742.html