简体   繁体   中英

iOS: NSMutableAttributedString.AddAttributes not rendered. (Xamarin)

I am trying to change the style of a link in a UILabel in Xamarin.iOS. I wrote the following code and the NSMutableAttributedString is updated correctly. However the updated style is not rendered. Am I missing something?

I am testing on the iOS Simulator.

mutableHtmlString.EnumerateAttribute(linkAttributeName, new NSRange(0, mutableHtmlString.Length), NSAttributedStringEnumeration.LongestEffectiveRangeNotRequired,
    (NSObject value, NSRange range, ref bool stop) =>
    {
        var attrHyperlink = new UIStringAttributes
        {
            UnderlineStyle = NSUnderlineStyle.None,
            ForegroundColor = UIColor.Red,
        };

        if (value != null && value is NSUrl url)
        {
            mutableHtmlString.AddAttributes(attrHyperlink, range);
            System.Diagnostics.Debug.WriteLine(@$"XXX: {mutableHtmlString}");
        }               
    });
control.AttributedText = mutableHtmlString;

NSUnderlineStyle.PatternDash is rendered correctly. Also KerningAdjustment and UnderlineColor.

Is this limitation of UILabel?

From Apple : To promote consistency, the intended behavior is for ranges that represent links (specified via NSLinkAttributeName) to be drawn using the default link appearance. So the current behavior is the expected behavior.

So this mean it's an UILabel limitation and it's intentional.

However, there is a workaround. Just replace NSLink with a custom attribute.

mutableHtmlString.EnumerateAttribute(linkAttributeName, new NSRange(0, mutableHtmlString.Length), NSAttributedStringEnumeration.LongestEffectiveRangeNotRequired,
    (NSObject value, NSRange range, ref bool stop) =>
    {
        var attrHyperlink = new UIStringAttributes
        {
            UnderlineStyle = NSUnderlineStyle.None,
            ForegroundColor = UIColor.Red,
        };

        if (value != null && value is NSUrl url)
        {
            mutableHtmlString.AddAttribute(customAttributeName, value, range);
            mutableHtmlString.RemoveAttribute("NSLink", range);
            mutableHtmlString.AddAttributes(attrHyperlink, range);
        }               
    });
control.AttributedText = mutableHtmlString;

The you can use customAttributeName to find the string if needed.

Thanks to https://exceptionshub.com/color-attribute-is-ignored-in-nsattributedstring-with-nslinkattributename.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM