Ian Warburton
Ian Warburton

Reputation: 15676

GestureRecognizer on Span doesn't fire when clicked on

The following code doesn't work:

var fs = new FormattedString();

fs.Spans.Add(new Span { Text = "\n\n" });

var telSpan = new Span { Text = "Hi Mum!" };

telSpan.GestureRecognizers.Add(new TapGestureRecognizer
{
   Command = new Command(() =>
   {
      // ...
   })
});

fs.Spans.Add(telSpan);

If I put a TapGestureRecognizer on the parent Label then that fires with no problems.

I have a Span with a GestureRecognizer elsewhere that's declared in XAML and it works fine.

What could be wrong here?

Upvotes: 3

Views: 1061

Answers (1)

Drytin
Drytin

Reputation: 366

Adding TapGestureRecognizers to each span in a Label. In this example, I then add the Label to a StackLayout.

var fs = new FormattedString();
foreach(var sentence in paragraph) 
{
     var span = new Span
     {
          Text = sentence.Message,
          TextColor = Color.FromHex("#222"),
          FontSize = 16,
     };
                
     span.GestureRecognizers.Add(new TapGestureRecognizer
     {
          Command = new Command(i =>
          {
               // On double tap the sentence Id will be written to the console.
               Console.WriteLine(i);
          }),
          CommandParameter = sentence.Id,
          NumberOfTapsRequired = 2 // removing this line will default number of taps to 1 
     });

     fs.Spans.Add(span);
}
// remove LineBreakMode = LineBreakMode.WordWrap if unnecessary.
someStackLayout.Children.Add(new Label { LineBreakMode = LineBreakMode.WordWrap, FormattedText = fs });

Upvotes: 1

Related Questions