[英]iOS: NSMutableAttributedString.AddAttributes not rendered. (Xamarin)
I am trying to change the style of a link in a UILabel in Xamarin.iOS.我正在尝试更改 Xamarin.iOS 中 UILabel 中链接的样式。 I wrote the following code and the NSMutableAttributedString is updated correctly.
我编写了以下代码,并且 NSMutableAttributedString 已正确更新。 However the updated style is not rendered.
但是,不会呈现更新的样式。 Am I missing something?
我错过了什么吗?
I am testing on the iOS Simulator.我正在 iOS 模拟器上进行测试。
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. NSUnderlineStyle.PatternDash 正确呈现。 Also KerningAdjustment and UnderlineColor.
还有字距调整和下划线颜色。
Is this limitation of UILabel?这是 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.来自 Apple :为了提高一致性,预期行为是使用默认链接外观绘制表示链接(通过 NSLinkAttributeName 指定)的范围。 So the current behavior is the expected behavior.
所以当前的行为是预期的行为。
So this mean it's an UILabel limitation and it's intentional.所以这意味着这是一个 UILabel 限制,它是故意的。
However, there is a workaround.但是,有一个解决方法。 Just replace NSLink with a custom attribute.
只需用自定义属性替换NSLink 即可。
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.如果需要,您可以使用
customAttributeName
来查找字符串。
Thanks to https://exceptionshub.com/color-attribute-is-ignored-in-nsattributedstring-with-nslinkattributename.html感谢https://exceptionshub.com/color-attribute-is-ignored-in-nsattributedstring-with-nslinkattributename.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.