zarax
zarax

Reputation: 831

How to make text selectable in Nativescript?

I want to make some texts selectable by user so that she can copy and paste it. How can I make a text in a Label element selectable in Nativescript on both Android and iOS?

Upvotes: 1

Views: 1320

Answers (2)

Mudlabs
Mudlabs

Reputation: 579

TextView

If you can change it to a TextView iOS will default to this behaviour.

  • Set `editable="false" so the user can't edit your text. And to prevent the keyboard from appearing.

  • iOS will apply a white background. Set `backgroundColor="transparent" to stop this.

  • On Android you will need to set args.object.nativeView.setTextIsSelectable(true) (i.e. from the views loaded event). You would need to do this even if you stick to using a Label.

<TextView 
  editable="false"
  text="Your text goes here"
  backgroundColor="transparent"
  android:loaded="makeSelectable" />
exports.makeSelectable = args => args.object.nativeView.setTextIsSelectable(true);

Label

If you want (or need) to stick to using a Label I'd say you have two options;

  1. If you want the user to be able to select just part of your text with the native text selection UI

    • For iOS look into UIMenuController.
    • For Android just setTextIsSelectable again.
  2. If you just want the user to be able to copy the whole text to clipboard, attach a longPress event to your Label. Then grab the object.text and add it to the clipboard, either by working with the native APIs or the Clipboard plugin. I recommend the plugin.

    • On iOS the longPress event will fire twice. So to make sure you don't copy the text twice you can check args.ios.state. This will return the constant 1 when the press begins, and 3 when it ends.

Upvotes: 3

Idrees Khan
Idrees Khan

Reputation: 7752

I had to do same thing in the past and i came up with HTMLView. The only thing i had to do was to use inline styling for fonts and other stuffs:

<HtmlView html="<span style='font-size:16px;color:#8f8f8f;margin:3px 0;font-family: Open Sans;'>{{oVPC.data}}</span>" textWrap="true" class="data" (tap)="onOpenLinkInWebBrowser(oVPC.data)"></HtmlView>

Upvotes: 0

Related Questions