我试图找到在xamarin.forms上显示本地pdf文件的方法。我找到了一个实现webview及其呈现的自定义实现的解决方案:pdf阅读器
主要代码是:
public class CustomWebView : WebView
{
public static readonly BindableProperty UriProperty = BindableProperty.Create<CustomWebView, string>(p => p.Uri, default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
}呈现:
[assembly: ExportRenderer (typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace DisplayPDF.iOS
{
public class CustomWebViewRenderer : ViewRenderer<CustomWebView, UIWebView>
{
protected override void OnElementChanged (ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged (e);
if (Control == null) {
SetNativeControl (new UIWebView ());
}
if (e.OldElement != null) {
// Cleanup
}
if (e.NewElement != null) {
var customWebView = Element as CustomWebView;
string fileName = Path.Combine (NSBundle.MainBundle.BundlePath, string.Format ("Content/{0}", WebUtility.UrlEncode (customWebView.Uri)));
Control.LoadRequest (new NSUrlRequest (new NSUrl (fileName, false)));
Control.ScalesPageToFit = true;
}
}
}
}我的页面是:
public class WebViewPageCS : ContentPage
{
public WebViewPageCS ()
{
webView = new CustomWebView
{
Uri = "ScalaReference.pdf",
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
}但是现在我找不到为这个pdf文件添加锚的方法,如本文所描述的:锚定至pdf
此外,我还尝试使用这段代码来评估脚本:
private async void Scroll_Clicked(object sender, EventArgs e)
{
webView.Eval($"window.scrollTo(0, {x});");
}它在默认的webview中工作得很好,但是与自定义的webview不一样。
也许有人知道另一种方式滚动/设置锚为pdf和链接到这个锚通过xamarin.forms?谢谢。
发布于 2018-05-30 09:49:40
它在默认的webview中工作得很好,但是与自定义的webview不一样。
它不是由自定义的webview造成的,因为呈现程序在UIWebview中为Control创建了一个新的CustomWebViewRenderer,请看下面的代码部分:
if (Control == null) {
SetNativeControl (new UIWebView ());
}因此,它在执行webView.Eval($"window.scrollTo(0, {x});");时不起作用,因为这个when视图实际上不是UIWebview。
解决方案
在BindableProperty中创建CustomWebView
public static readonly BindableProperty AnchorProperty = BindableProperty.Create<CustomWebView, float>(p => p.Anchor, default(float));
public float Anchor
{
get { return (float)GetValue(AnchorProperty); }
set { SetValue(AnchorProperty, value); }
}在页面中触发它
private void Scroll_Clicked(object sender, System.EventArgs e)
{
webview.Anchor = 200;
}获取渲染器中的值并使webview滚动。
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if(e.PropertyName is "Anchor")
{
var customWebView = Element as CustomWebView;
float anchor = customWebView.Anchor;
Control.ScrollView.ContentOffset = new CoreGraphics.CGPoint(0, anchor);
}
}https://stackoverflow.com/questions/50584588
复制相似问题