How do you allow users to copy and paste from an Xamarin.Forms label

后端 未结 2 776
终归单人心
终归单人心 2021-02-13 21:30

How do you allow users to copy and paste from an Xamarin.Forms Label?

Click on the text on any platform the default settings don\'t allow highlighting and therefore cop

2条回答
  •  庸人自扰
    2021-02-13 21:53

    What you could do is wrap your label in a gesture recogniser:

    
    

    This will trigger your function and in that function you can get to the clipboard and copy and paste. However I haven't been able to find an easy way to access the clipboard in Xamarin.Forms so you have to use the dependency service.

    Xamarin.Forms Dependency service documentation

    Here is how I did my clipboard data access. Please note that in my project I only needed to nab data from the clipboard so this code just shows you how to access the clipboard data:

    1. Create an interface in you X.F project eg:

          public interface IClipBoard
          {
              String GetTextFromClipBoard();
          }
      
    2. Implement the interface in your mobile projects:

      Android:
          public string GetTextFromClipBoard ()
          {
              var clipboardmanager = (ClipboardManager)Forms.Context.GetSystemService (Context.ClipboardService);
              var item = clipboardmanager.PrimaryClip.GetItemAt(0);
              var text = item.Text;
              return text;
          }
      
      iOs:
          public string GetTextFromClipBoard ()
          {
              var pb = UIPasteboard.General.GetValue ("public.utf8-plain-text");
              return pb.ToString ();
          }
      

    Don't forget to add the Assembly bits at the top:

        iOs: [assembly: Dependency (typeof (ClipBoard_iOs))]
        Android: [assembly: Dependency (typeof (ClipBoard_Droid))]
    
    1. Call the dependency service from you X.F function

          public void YourFunctionToHandleMadTaps(Object sender, EventArgs ea)
          {
              var clipboardText = DependencyService.Get ().GetTextFromClipBoard ();
      
              YourFunctionToHandleMadTaps.Text = clipboardText;
          }
      

提交回复
热议问题