c# – 在iOS上为内部导航引发的Xamarin.Forms.WebView.Navigating事件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 在iOS上为内部导航引发的Xamarin.Forms.WebView.Navigating事件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2418字,纯文字阅读大概需要4分钟。
内容图文
假设您要阻止用户从您的Xamarin.Forms.WebView导航到外部页面.
public App ()
{
var webView = new WebView
{
Source = new HtmlWebViewSource
{
Html = "<h1>Hello world</h1><a href='http://example.com'>Can't escape!</a><iframe width='420' height='315' src='https://www.youtube.com/embed/oHg5SJYRHA0' frameborder='0' allowfullscreen></iframe>"
}
};
webView.Navigating += WebView_Navigating;
MainPage = new ContentPage {
Content = webView
};
}
private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
{
// we don't want to navigate away from our page
// open it in a new page instead etc.
e.Cancel = true;
}
这适用于Windows和Android.但在iOS上,它根本不加载!
在iOS上,即使从HtmlWebViewSource加载源代码时,也会引发Navigating事件,其URL类似于file:/// Users / [user] / Library / Developer / CoreSimulator / Devices / [deviceID] / data / Containers /Bundle/Application/[appID]/[appName].app/
好吧,所以你可以用这样的东西解决这个问题:
private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
{
if (e.Url.StartsWith("file:") == false)
e.Cancel = true;
}
该页面最终在iOS上加载.好极了.可是等等!嵌入的YouTube视频无法加载!那是因为导航事件被引发用于嵌入式资源的内部导航,例如iframe甚至外部脚本(如Twitter的< script charset =“utf-8”type =“text / javascript”src =“http://platform.twitter .com / widgets.js“>< / script>),但仅限iOS!
我找不到确定导航事件是从内部导航引发还是因为用户单击链接的方法.
怎么解决这个问题?
解决方法:
我不确定是否可以开箱即用Xamarin Forms进行检测,但使用自定义渲染器可以轻松确定导航类型.在您的自定义iOS渲染器中,分配WebViewDelegate并在该Delegate类中,覆盖ShouldStartLoad(),如下所示:
public class CustomWebViewRenderer : WebViewRenderer {
#region Properties
public CustomWebView CustomWebViewItem { get { return Element as CustomWebView; } }
#endregion
protected override void OnElementChanged(VisualElementChangedEventArgs e) {
base.OnElementChanged(e);
if(e.OldElement == null) {
Delegate = new CustomWebViewDelegate(); //Assigning the delegate
}
}
}
internal class CustomWebViewDelegate : UIWebViewDelegate {
public override bool ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType) {
if(navigationType == UIWebViewNavigationType.LinkClicked) {
//To prevent navigation when a link is click, return false
return false;
}
return true;
}
}
你也可以将一个bool属性甚至一个枚举表示回到你的Xamarin Forms WebView,它会说明导航事件是来自被点击的链接还是来自其他东西,尽管也需要自定义渲染器.
内容总结
以上是互联网集市为您收集整理的c# – 在iOS上为内部导航引发的Xamarin.Forms.WebView.Navigating事件全部内容,希望文章能够帮你解决c# – 在iOS上为内部导航引发的Xamarin.Forms.WebView.Navigating事件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。