2

I am learning mobile app development and I am trying to add a link to a label, and would like some guidance and this is the code for the label

     var LinkLabel = new UILabel()
        {
            Frame = new CGRect(20, 170, View.Bounds.Width - 40, 40),
            TextColor = UIColor.Blue,
            TextAlignment = UITextAlignment.Center,
            Font = UIFont.SystemFontOfSize(24),
            Text = "Label",
        };
sisi
  • 355
  • 2
  • 12

2 Answers2

0

I think you need code in Xamarin.iOS:

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    // Perform any additional setup after loading the view, typically from a nib.

    var LinkLabel = new UILabel()
    {
        Frame = new CGRect(20, 170, View.Bounds.Width - 40, 40),
        TextColor = UIColor.Blue,
        TextAlignment = UITextAlignment.Center,
        Font = UIFont.SystemFontOfSize(24),
        Text = "Label",
        UserInteractionEnabled = true
    };

    Add(LinkLabel);

    Action action = () => {

        UIApplication.SharedApplication.OpenUrl(new NSUrl("https://www.google.com"));

    };

    UITapGestureRecognizer tapGes = new UITapGestureRecognizer(action);
    LinkLabel.AddGestureRecognizer(tapGes);
}

You can easily add a UITapGestureRecognizer to the label and handle the event when user click it. Remember to set label's UserInteractionEnabled to true.

If you want the whole text is clickable, you can use a button instead.

If you want part of the text is clickable, you should use NSMutableAttributedString, you can check the answer in this thread, I can help you to translate the solutions to C# if you need.

nevermore
  • 15,432
  • 1
  • 12
  • 30
-1

with this code, you can add action to your label

 let tap = UITapGestureRecognizer(target: self, action: #selector(yourAction(sender:)))
 LinkLabel.addGestureRecognizer(tap)

 @objc func yourAction(sender:UITapGestureRecognizer) {
    let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertController.Style.alert)
    let action = UIAlertAction(title: "link", style: .default, handler: nil)
    alert.addAction(action)
    self.present(alert, animated: true, completion: nil)
}

in the handler says nil because when your click the alert controller, the action will be close the view

Andres Gomez
  • 458
  • 3
  • 12