☰
UIWebView,移动web
2026/9/28 1:03:29 网站建设 项目流程

1.只有使用loadRequest:加载网页,才能对之后的链接操作做goBack,goForward操作,即canGoBack,canGoForward才有可能返回YES.

使用loadHTMLString,loadData都不可以.

并且在load之后通过stringByEvaluatingJavaScriptFromString对网页增加的内容,在

NSString* outerHTML = [iWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];//document.documentElement.innerHTML

中都不会出现。

3.goBack也会请求页面,也会回调代理方法.

4. NSURLErrorDomain error -999.

This error may occur if an another request is made before the previous request of WebView is completed...

I worked around this by ignoring this error and letting the webview continue to load.

5.双击一个图片链接不会调用到shouldStartLoadWithRequest

判断点击到的是否是图片,可设置特殊的url,或判断当前点击的tag,使用window.pageYOffset,window.pageXOffset,window.outerWidth,document.elementFromPoint等。

例如 NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", pt.x, pt.y];,

js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).getAttribute('_src')", pt.x, pt.y];
获取自定义属性的值时,用getAttribute。

7.设置背景色后,如下:iWebView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];

当内容很长时,会占用很大内存,这说明它会根据ContentSize平铺,而不是Bounds;

使用iWebView.backgroundColor=[UIColor blackColor];则不会占用这么大的内存。

8.webView_.opaque = NO;//设置webView最上面的内容的背景透明

webView_.backgroundColor=[UIColor clearColor];//设置其中的scrollView透明

使用图片背景的方案是:在iWebView的下面同级加一层UIImageView, iWebView.backgroundColor=[UIColor clearColor];,当内容拖动到头或尾时,会透出iWebView下面的背景。

如果要让内容的背景也透明,再设置不透明属性为NO:webView.opaque = NO;

利用这些属性可以实现在顶部或底部拖动时,展现刷新提示效果;

8.在顶部和底部时,禁用拖动回弹:
for (id subview in iWebView.subviews)
{
if ([[subview class] isSubclassOfClass: [UIScrollView class]])
{
((UIScrollView *)subview).bounces = NO;
}
}


禁止UIWebView的bounces
http://www.flyblog.info/catprogramming/303.html


底部灰色阴影其实是个imageview,hidden就行了,不影响任何正常操作:
for(UIView *v in [[[iWebView subviews] objectAtIndex:0] subviews])
{
if([v isKindOfClass:[UIImageView class]])
{
v.hidden = YES;
}
}

或者

for (UIView *shadowView in [webView_.scrollView subviews])
{
if ([shadowView isKindOfClass:[UIImageView class]])
{
shadowView.hidden = YES;
}
}

或者

// remove shadow view when drag web view for (UIView *subView in [webView_ subviews]) { if ([subView isKindOfClass:[UIScrollView class]]) { for (UIView *shadowView in [subView subviews]) { if ([shadowView isKindOfClass:[UIImageView class]]) { shadowView.hidden = YES; } } } }for (UIView *subView in [webView_ subviews]) { if ([subView isKindOfClass:[UIScrollView class]]) { for (UIView *shadowView in [subView subviews]) { if ([shadowView isKindOfClass:[UIImageView class]]) { shadowView.hidden = YES; } } } }

让网页自适应屏幕

webview.scalesPageToFit = YES;

在网页中写下面的js代码,也可以实现bounces = NO的功能

document.onload = function(){ document.ontouchmove = function(e){ e.preventDefault(); } }

9.由此服务端日志记录可知,iphone端safiri及UIWebView的图片缓存是没有的。每次访问都需要从服务端重新下载图片

http://tangqiaoboy.blog.163.com/blog/static/11611425820118672051584/

cachePolicy:NSURLRequestUseProtocolCachePolicy???

对同一个设置为本地src的img,UIWebView总是缓存其内容,重建UIWebView依旧。只能重新启动软件。在图片地址后加上@"?t=%ld",time(NULL) ,

localPath=[localPath stringByAppendingFormat:@"?t=%ld",time(NULL) ];,再loadHtml,可解决问题。原理是在图片后面加了一个随机数,让浏览器不再读取缓存。

http://stackoverflow.com/questions/11516278/how-to-clear-cache-for-my-uiwebviews-loadhtmlstring

http://www.techques.com/question/1-11516278/How-to-clear-cache-for-my-UIWebView's-loadHtmlString

10.UIWebView的stringByEvaluatingJavaScriptFromString只能在主线程里面被调用,如果恰好这个js执行时间比较长,就会造成程序卡死。

跟 Mac OS X 比较起来,iPhone 上 UIWebView 的公开 API 实在少上许多.

http://spring-studio.net/?p=265

11.UIWebView之获取所点位置图片URL

http://www.cocoachina.com/newbie/basic/2011/1031/3439.html

14.禁用UIWebView中双击和手势缩放页面,但测试结果是缩小了一半,确实不影响双击了,但不缩小时仍然响应双击上下滚动。

http://blog.163.com/alex_kame/blog/static/14546748201171263254740/

http://learnthemobileweb.com/2009/07/mobile-meta-tags/

16. UIWebView处理authentication方法
参考 http://www.cocoachina.com/newbie/basic/2011/1123/3583.html

17.elementFromPoint() under iOS 5
http://www.icab.de/blog/2011/10/17/elementfrompoint-under-ios-5/

NSString* js = [NSString stringWithFormat:@"elementFromViewportPoint(%f, %f).tagName", pt.x, pt.y];

//private

function viewportCoordinateToDocumentCoordinate(x,y)
{
var coord = new Object();
coord.x = x + window.pageXOffset;
coord.y = y + window.pageYOffset;
return coord;
}

//private

function elementFromPointIsUsingViewPortCoordinates()
{
if (window.pageYOffset > 0)
{
// page scrolled down
return (window.document.elementFromPoint(0, window.pageYOffset + window.innerHeight -1) == null);
}
else if (window.pageXOffset > 0)
{
// page scrolled to the right
return (window.document.elementFromPoint(window.pageXOffset + window.innerWidth -1, 0) == null);
}

return false; // no scrolling, don't care
}

//public

function elementFromViewportPoint(x,y)
{
if (elementFromPointIsUsingViewPortCoordinates())
{
return window.document.elementFromPoint(x,y);
}
else
{
var coord = viewportCoordinateToDocumentCoordinate(x,y);
return window.document.elementFromPoint(coord.x,coord.y);
}
}

内容高度 : int contentHeight=[[webView_ stringByEvaluatingJavaScriptFromString:@"document.body.clientHeight"] intValue];

18.滚动到顶部

[webView_ stringByEvaluatingJavaScriptFromString:@"window.scrollTo(0,0);"];

19.在UIGestureRecognizer的响应函数中调用打开一个有输入框的页面,UIGestureRecognizer的响应中后续会让webview再次获得焦点,从而使键盘隐藏。

这样把事件放到shouldStartLoadWithRequest中来曲线解决问题。

20. webapp是css+html来描述的,没办法简单的用name@2x 解决问题,继续求教中

iphone4图片问题

http://aralbalkan.com/3331

在head中添加 <meta name="viewport" content="width=device-width, initial-scale=0.5, minimum-scale=0.5, maximum-scale=yes" />

<meta align="center" name="viewport" content="width=480; initial-scale=0.5; maximum-scale=0.5; user-scalable=no;"/>

也可以控制页面的缩放,但并不统一。

为视网膜显示屏优化网页上的图片
(via:http://xuui.net/ui-design/retinal-display-to-optimize-the-image-the-on-the-the-page.html).

在网页中,pixel 与 point 比值称为 device-pixel-ratio,普通设备都是1,iPhone 4是2,有些Android机型是1.5。

Detecting taps and events on UIWebView – The right way

http://mithin.in/2009/08/26/detecting-taps-and-events-on-uiwebview-the-right-way

21.对UIWebView中的数据的网络请求,js操作,一定要放到webViewDidFinishLoad调用之后,否则很可能出现找不到标签的异常问题。!!

html模板中,把要替换的内容放在div中,不要放在p中,否则不保证样式正常显示。

22.在顶部向下拖动一段距离的事件

UIScrollView* scrollView = [webView_.subviews objectAtIndex:0];
if (scrollView && [scrollView isKindOfClass:[UIScrollView class]])
{
scrollView.delegate = self;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
CGPoint offset = scrollView.contentOffset;
NSLog(@"%@",NSStringFromCGPoint(offset));
if(offset.y<=-60.0)
{
[super onNavigationBackPressed];
}
}

23.

webView_=[[UIWebView alloc] initWithFrame:webRect];
webView_.delegate=self;
webView_.dataDetectorTypes = UIDataDetectorTypeNone;
webView_.opaque = NO; //背景透明
webView_.backgroundColor=[UIColor whiteColor];


[self.view addSubview:webView_];
self.view.backgroundColor=[UIColor blackColor];

//隐藏灰影
for(UIView *v in [[[webView_ subviews] objectAtIndex:0] subviews])
{
if([v isKindOfClass:[UIImageView class]])
{
v.hidden = YES;
}
}

//拖动事件
UIScrollView* scrollView = [webView_.subviews objectAtIndex:0];
if (scrollView && [scrollView isKindOfClass:[UIScrollView class]])
{
scrollView.delegate = self;
}

//圆角
[[webView_ layer] setCornerRadius:10];
[webView_ setClipsToBounds:YES];
[[webView_ layer] setBorderColor:[[UIColor blackColor] CGColor]];
//[[webView_ layer] setBorderWidth:2.75];

[(UIScrollView *)[[webview subviews] objectAtIndex:0] setBounces:NO];

24. 取得选中的内容

给UIWebView增加类别

- (NSString *)selectedText {
return [self stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"];
}

25.iphone web框架

iUi http://code.google.com/p/iui/ 它是一个javascript和css库,用于在网页中模拟iphone的外观和感觉。虽然是专为iphone设计的UI,但在android上90%以上的功能是完全可以使用的,因为android和iphone一样,都是基于webkit浏览器的系统。

iUI框架:用Eclipse开发iOS Web应用程序
http://www.61ic.com/Mobile/iPhone/201203/41389.html

26.[iOS]给UIWebView头尾插入自定义View

http://blog.cnbang.net/tech/1784/

示例代码下载:

https://github.com/bang590/iOSPlayground/tree/master/TWebview

11个基本的移动Web编程工具

http://developer.51cto.com/art/201107/273822.htm

27.iOS 5中safari带来的新特性

http://www.qianduan.net/ios-5-brings-new-features-in-safari.html

28.HTML5 Showcase

http://www.apple.com/html5/showcase/typography/

29.不用UIWebView辅助排版的困难

表情图片混在文字中;

图片后加载,大小不一,使列表跳动;

预知图片尺寸,或固定尺寸;

30.点击UIImageView打开键盘,未测试

http://android-zhang.iteye.com/blog/1758562

31.手机版网页的table优化处理 (未使用过)

http://www.liubiao4123.com/table_mobile.html

32.在UIWebView上追加菜单项

http://blog.csdn.net/andyweike/article/details/6061096

33.关于UIWebView的那些事儿(更新中)

http://www.lanou3g.com/blog/post-163.html

34.使用base64

http://iphoneincubator.com/blog/windows-views/display-images-in-uiwebview 未使用过

<h1>stringByEvaluatingJavaScriptFromString</h1>
android平台中调用WebView控件的addJavascriptInterface()方法可以轻松完成很多交互,在IOS中会困难复杂一些。
<h3>主程序主动通知UIWebView</h3>
<pre>[webView stringByEvaluatingJavaScriptFromString:@"some js code"];</pre>
<h3>UIWebView主动通知主程序</h3>
UIWebView通过js设置document.location = url; 会触发shouldStartLoadWithRequest接口被调用,并且返回NO。url字符串格式可自定义,把命令及参数封装到其中。
<h1>通过js设置一些webkit属性</h1>
<pre> - (void)webViewDidFinishLoad:(UIWebView*)webView
{
//Disable user selection 禁用长按UIWebView时放大镜及选择功能:
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
//Disable callout,禁止长按链接弹出菜单,默认带有打开,拷贝,取消3个菜单项。
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
//修改整个页面的字体大小
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '150%';"];
//修改点击链接时的高亮背景色
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTapHighlightColor='#FF0000';"];
}</pre>
<h3>嵌入在页面中 修改点击链接时的高亮背景色</h3>
&lt;a style="-webkit-tap-highlight-color: rgba(0,0,0,0);" href="http://yourlink.com/"&gt;

更多参考webkit webApp 开发技术要点总结
<a href="http://www.cnblogs.com/pifoo/archive/2011/05/28/webkit-webapp.html">http://www.cnblogs.com/pifoo/archive/2011/05/28/webkit-webapp.html</a>
<h1>使用UIWebView显示svg、gif</h1>
SVG:Scalable Vector Graphics,可缩放矢量图形,是用XML描述二维矢量图形的一种图形格式。
若使用img标签,&lt;img src='' &gt;标签中src要带有.svg扩展名才可正常显示。
<pre>CGRect rect = CGRectMake(0,0,1000,1000);
webView = [[UIWebView alloc] initWithFrame:rect];
[webView loadData:svgData MIMEType:@"image/svg+xml" textEncodingName:@"UTF-8" baseURL:nil];

[webView loadData:gifData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];</pre>
<h1>使用UIWebView显示本地html文件</h1>
<h3>显示安装包中的html文件</h3>
<pre>NSString* pathInBundle=[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"app-guide" forLocalization:nil];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pathInBundle]]];
或者
[webView_ loadHTMLString:htmlContent baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];</pre>
这里的重点是使用loadRequest,且使用fileURLWithPath而不是URLWithString。

如果要显示一段html内容,且其中有防盗链网络图片,则需要修改baseURL为Referer地址,例如:
<pre>[webView loadHTMLString:htmlContent baseURL:[NSURL URLWithString:@"http://a.cn"]];</pre>
<h3>动态设置img地址</h3>
<pre>NSString* path=[FileUtil getDocumentsFullPath:@"logo.png"];
NSString* path=[[NSBundle mainBundle] pathForResource:@"logo" ofType:@"png"];
path=[NSString stringWithFormat:@"file://%@",path]; //file后面是冒号加3个斜杠
NSString* script=[NSString stringWithFormat:@"setImgSrc(\"%@\");",path];
[webView stringByEvaluatingJavaScriptFromString:script];</pre>
<h1>NSHTTPCookieStorage</h1>
<pre>- (void)addCookies:(NSString *)domain withCookies:(NSArray *)cookieArray
{
NSHTTPCookie *cookie = nil;
NSDictionary *properties = nil;
NSString* cookieStr = nil;
for (int i=0; i&lt;[cookieArray count]; i++)
{
cookieStr = [cookieArray objectAtIndex:i];
NSRange range = [cookieStr rangeOfString:@"="];
if(range.location != NSNotFound)
{
properties = [NSDictionary dictionaryWithObjectsAndKeys:
[cookieStr substringToIndex:range.location], NSHTTPCookieName,
[cookieStr substringFromIndex:range.location+range.length], NSHTTPCookieValue,
@"/", NSHTTPCookiePath,
domain, NSHTTPCookieDomain,
nil];
}
cookie = [NSHTTPCookie cookieWithProperties:properties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}

- (void)clearCookies
{
NSHTTPCookie *cookie = nil;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
[storage deleteCookie:cookie];
}
}</pre>

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询