首页 > 解决方案 > 向 UIlabel 添加超链接

问题描述

我正在学习移动应用程序开发,我正在尝试向标签添加链接,并需要一些指导,这是标签的代码

     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",
        };

标签: iosswiftxamarin.ios

解决方案


我认为您需要 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);
}

您可以轻松地将 a 添加UITapGestureRecognizer到标签并在用户单击它时处理事件。请记住将标签设置UserInteractionEnabled为 true。

如果您希望整个文本都是可点击的,您可以使用按钮来代替。

如果您希望部分文本是可点击的,您应该使用,您可以在此线程NSMutableAttributedString中查看答案,如果您需要,我可以帮助您将解决方案翻译成 C#。


推荐阅读