在UITextView中打开没有html的点击链接



我已经使用Texture(以前的AsyncDisplayKit(很长时间了,并且习惯于能够在ASTextNode中轻松点击电话号码和链接。

然后我切换到一个旧的 xamarin 项目,并且需要相同的功能。我一直在努力为这个问题找到正确而简单的解决方案,并发现人们建议使用 UIWebView 和类似的东西。

这有点棘手,所以我将尝试描述我在解决这个问题时想出的一些步骤。

  • 尝试解析字符串以获取可能的链接。 在我的情况下,字符串是总是一组电话号码,例如 - "88002000600 +79999999998888800888"所以这是一个简单的案例,但应该不是问题解析网站链接,正则表达式的电子邮件。
  • 组成属性字符串并分配必要的属性,如下所示

--

//something right here and get your potential links list
    var attributedContacts = new NSMutableAttributedString (value as string, UIFont.SystemFontOfSize (14), UIColor.White, UIColor.Clear);
                foreach (var item in numbers) {
                    var nsStringItem = new NSString (item);
                    var nsTelPromptLink = new NSString (string.Format ("telprompt://{0}", item));
                    var range = attributedContacts.MutableString.LocalizedStandardRangeOfString (nsStringItem);
                    attributedContacts.AddAttribute (new NSString ("TextLinkAttributeName"), nsTelPromptLink, range);
                }
                textView.AttributedText = attributedContacts;
  • 然后,应将手势识别器添加到文本视图和句柄点击以下方式:

--

var tapRecognizer = new UITapGestureRecognizer ((UITapGestureRecognizer recognizer) => {
                var textView = recognizer.View as UITextView;
                if (textView == null)
                    return;
                var tappedPoint = recognizer.LocationInView (textView);
                tappedPoint.X -= textView.TextContainerInset.Left;
                tappedPoint.Y -= textView.TextContainerInset.Top;
                var layoutManager = textView.LayoutManager;
                nfloat tmp = 0;
                var tappedCharacterIndex = layoutManager.CharacterIndexForPoint (tappedPoint, textView.TextContainer, ref tmp);
                NSRange range = new NSRange ();
                var url = textView.AttributedText.GetAttribute ("TextLinkAttributeName", (nint)tappedCharacterIndex, out range) as NSString;
                if (url == null)
                    return;
                UIApplication.SharedApplication.OpenUrl (new NSUrl (url.ToString ()));
            });
            ContactsTextView.AddGestureRecognizer (tapRecognizer);

所以,这是一个相当粗略的解决方案,应该有额外的检查,但我认为这个想法本身很清楚。它可以很容易地应用于 Swift 或 Objective-C 中的原生解决方案。

最新更新