如何在xamarin.ios的UITextView中更改链接颜色

时间:2018-10-01 12:55:46

标签: xamarin xamarin.ios

我们已使用此代码在UITextView中创建了可点击的文本

   var urlString = @"<a href=""https://www.google.com"" >Google</a>";
        var documentAttributes = new NSAttributedStringDocumentAttributes { DocumentType = NSDocumentType.HTML };
        NSError error = null;
        var attributedString = new NSAttributedString(NSData.FromString(urlString, NSStringEncoding.UTF8), documentAttributes, ref error);
        // Should really check the NSError before applying

        MyTextView.AttributedText = attributedString;

,但默认情况下,链接和带下划线的文本显示为蓝色。我们要更改文本的颜色,还要删除下划线。 请指导/帮助我实现这一目标。

1 个答案:

答案 0 :(得分:1)

只需将UIStringAttributeKey.ForegroundColor和UIStringAttributeKey.UnderlineStyl添加到字典并将其设置为WeakLinkTextAttributes属性即可更改这些属性

var key1 = UIStringAttributeKey.ForegroundColor;
var value1 = UIColor.Red;

var key2 = UIStringAttributeKey.UnderlineStyle;
var value2 = new NSNumber(0); // 0 without underline 1 with underline

var dict = new NSDictionary(key1, value1, key2, value2);

var urlString = @"<a href=""https://www.google.com"" >Google</a>";
var documentAttributes = new NSAttributedStringDocumentAttributes { 
           DocumentType = NSDocumentType.HTML };
NSError error = null;
var attributedString = new NSAttributedString(NSData.FromString(urlString, NSStringEncoding.UTF8), documentAttributes, ref error);

yourTextView.AttributedText = attributedString;
yourTextView.WeakLinkTextAttributes = dict;