How to change link color in UITextView in xamarin.

2019-08-17 08:13发布

问题:

We have created a clickable text in UITextView by using this code

   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;

but its showing by default blue color for the link and underlined text. We want to change the color for the text and also remove underline. Please guide/help me to implement this.

回答1:

You can change these properties just adding UIStringAttributeKey.ForegroundColor and UIStringAttributeKey.UnderlineStyl to your dictionary and set it to WeakLinkTextAttributes property

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;