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

后端 未结 2 783
终归单人心
终归单人心 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:37

    Since I_Khanage provided only a half solution, I will post the full solution.

    IClipboardService should be implemented for all the targeting platforms, in my case it is Android and iOS:

    public interface IClipboardService
    {
        string GetTextFromClipboard();
        void SendTextToClipboard(string text);
    }
    
    // iOS
    public class ClipboardService : IClipboardService
    {
        public string GetTextFromClipboard() => UIPasteboard.General.String;
        public void SendTextToClipboard(string text) => UIPasteboard.General.String = text;
    }
    
    // Android
    public class ClipboardService : IClipboardService
    {
        public string GetTextFromClipboard()
        {
            var clipboardmanager = (ClipboardManager)Forms.Context.GetSystemService(Context.ClipboardService);
            var item = clipboardmanager.PrimaryClip.GetItemAt(0);
            var text = item.Text;
            return text;
        }
    
        public void SendTextToClipboard(string text)
        {
            // Get the Clipboard Manager
            var clipboardManager = (ClipboardManager)Forms.Context.GetSystemService(Context.ClipboardService);
    
            // Create a new Clip
            var clip = ClipData.NewPlainText("YOUR_TITLE_HERE", text);
    
            // Copy the text
            clipboardManager.PrimaryClip = clip;
        }
    }
    

    The code is available on github.

    Now just add a GestureRecognizer in order to trigger the tap event.

    P.S.: Clipboard service is now available as a part of Xamarin.Essentials package, so there is no need to write one yourself.

提交回复
热议问题