首页 > 解决方案 > (Android 和 iOS)Xamarin - 如何从 WebView 中获取点击/选定的文本或段落?

问题描述

如何从 WebView 中获取选定的文本范围?是否有诸如 selectedSomething 之类的 WebView 自定义事件?

--

如果没有解决方案;

我可以从 Webview 获取复制的文本/段落吗?复制的是否有事件(可能是自定义)?

--

我很乐意提供任何帮助。

标签: xamarin.formswebview

解决方案


在我们选择字符串后,选择会很快消失。该解决方案来自 Xamarin 论坛中的 ColeX。该选择适用于创建自定义渲染器并用 WKWebView 替换默认 webview。

https://forums.xamarin.com/discussion/comment/396734

自定义WebView

public class CustomWebView : WebView
{
    public static readonly BindableProperty UriProperty = BindableProperty.Create(
        propertyName: "Uri",
        returnType: typeof(string),
        declaringType: typeof(CustomWebView),
        defaultValue: default(string));

    public string Uri
    {
        get { return (string)GetValue(UriProperty); }
        set { SetValue(UriProperty, value); }
    }
}

主页

  //xmlns:local ="clr-namespace:App1"
<local:CustomWebView Uri="https://docs.microsoft.com/en-us/xamarin/ios/" HeightRequest="300"/>

自定义渲染器

[assembly: ExportRenderer(typeof(CustomWebView), typeof(HybridWebViewRenderer))]
namespace App1.iOS
{
    class HybridWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
    {

        protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var webView = new WKWebView(Frame, new WKWebViewConfiguration());
                SetNativeControl(webView);
            }
            if (e.NewElement != null)
            {
                Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Uri)));
            }
        }

    }
}

检测 Copy 事件的事件 将代码放在自定义渲染器或 AppDelegate 中。

 NSNotificationCenter.DefaultCenter.AddObserver(UIPasteboard.ChangedNotification,(noti)=> {
     var s = UIPasteboard.General.String;
     MessagingCenter.Send<object,string>(this, "Hi",s);
  },null);

演示


推荐阅读