我正在尝试更改Xamarin.iOS中UILabel中链接的样式。
我编写了以下代码,并且NSMutableAttributedString已正确更新。
但是,不会呈现更新的样式。
我想念什么吗?
我正在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正确呈现。
还有KerningAdjustment和UnderlineColor。
这是UILabel的限制吗?
最佳答案
来自苹果公司:为了提高一致性,预期的行为是使用默认链接外观绘制表示链接(通过NSLinkAttributeName指定)的范围。因此,当前行为是预期行为。
因此,这意味着它是UILabel的限制,而且是故意的。
但是,有一种解决方法。只需将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;
如果需要,您可以使用
customAttributeName
查找字符串。感谢https://exceptionshub.com/color-attribute-is-ignored-in-nsattributedstring-with-nslinkattributename.html
关于ios - iOS:未呈现NSMutableAttributedString.AddAttributes。 (Xamarin),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60580055/