近來做了個項目基本上都是加載Web頁矾麻,心里那是一個爽啊,都是直接給個鏈接完事险耀,太他媽爽了,根本都不用寫界面蘑志,爽爽爽贬派。。赠群。
這種加載Web頁開發(fā)的方式有啥優(yōu)缺點呢?
優(yōu)點:節(jié)省開發(fā)時間和成本突委。當然我們移動端開發(fā)基本上搭個架子就完事了
缺點:體驗不好冬三。
隨著項目的推進,為了讓用戶不覺的這是加載Web頁的空殼子勾笆,我發(fā)現(xiàn)還是有很多問題和知識我是欠缺的
遇到的問題
- 如何在Web 頁內(nèi)返回上一級
- 如何獲取網(wǎng)頁的title顯示在我們的導(dǎo)航欄上
- 如何關(guān)閉在Web 頁長按彈出網(wǎng)頁鏈接的現(xiàn)象(如下圖所示)
- 如何關(guān)閉下拉上拉時露底的現(xiàn)象
- 如何獲取即將加載網(wǎng)頁URL
- 如何在加載失敗后不出現(xiàn)404的字樣呢
- 如何修改Web頁提示的Alert title是網(wǎng)址的方法
在寫解決方法之前呢窝爪,我們先了解一下WebView傳送門
如何解決遇到的問題
<a id = "1">加載Web頁如何返回上一級</a>
@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
//獲取能否返回上一級
-- (void)goBack;
//返回上一級
if ([_webView canGoBack]) {
[_webView goBack];
} else {
[self.navigationController popViewControllerAnimated:YES];
}
<a id = "2">- 如何獲取網(wǎng)頁的title顯示在我們的導(dǎo)航欄上</a>
-- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
//通過javaScript操作web數(shù)據(jù)
self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];//一定要寫@“document.title”
<a id = "3">- 如何關(guān)閉在Web 頁長按彈出網(wǎng)頁鏈接的現(xiàn)象</a>
-(void)webViewDidFinishLoad:(UIWebView*)theWebView{
[self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
[self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
}
<a id = "4">- 如何關(guān)閉下拉上拉時露底的現(xiàn)象</a>
-(void)webViewDidFinishLoad:(UIWebView*)theWebView{
[(UIScrollView *)[[self.webView subviews] objectAtIndex:0] setBounces:NO];
}
<a id = "5">- 如何獲取即將加載網(wǎng)頁URL</a>
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString * requestString = request.URL.absoluteString;
NSLog(@"這個就是即將加載的URL可以拿到做一些事情:%@",requestString);
NSLog(@"%ld",(long)navigationType);
NSHTTPURLResponse *response = nil;
return YES;
}
<a id = "6">- 如何在加載失敗后不出現(xiàn)404的字樣呢</a>
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if (response.statusCode != 200) {
UIImageView *imageV = [[UIImageView alloc] init];
imageV.frame = [UIScreen mainScreen].bounds;
imageV.image = [UIImage imageNamed:@"失敗背景圖"];
[self.webView addSubview:imageV];
return NO;
}
return YES;
}
<a id = "7">- 如何修改Web頁提示的Alert title是網(wǎng)址的方法</a>
1.我們需要創(chuàng)建一個WebView的分類,寫上下面的代碼 運行試試 完美解決
.h
@interface UIWebView (hr_ent)
-(void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame;
@end
.m
@implementation UIWebView (hr_ent)
-(void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame {
UIAlertView* customAlert = [[UIAlertView alloc] initWithTitle:@""
message:message
delegate:nil
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[customAlert show];
}
@end