【发布时间】:2013-12-05 16:47:37
【问题描述】:
我在 UITextView 中有一个 NSAttributedString,其文本具有多个属性(粗体/斜体等)
我正在尝试检测将哪种样式应用于文本的选定部分以启用或禁用各种按钮:
NSRange selectionRange = GetSelectedTextRange();
NSMutableAttributedString text = new NSMutableAttributedString(ActiveTextInput.AttributedText);
NSDictionary attributesDictionary = text.GetAttributes(selectionRange.Location, out selectionRange);
text.EnumerateAttributes(selectionRange, NSAttributedStringEnumeration.LongestEffectiveRangeNotRequired, (NSDictionary attributes, NSRange range, ref bool stop) =>
{
if (attributes.ObjectForKey(CTStringAttributeKey.UnderlineStyle).Equals(NSUnderlineStyle.Single))
{
Console.WriteLine("UNDERLINED");
stop = true;
}
else
{
Console.WriteLine("NON UNDERLINED");
}
});
protected NSRange GetSelectedTextRange()
{
NSRange selectionRange = new NSRange(
ActiveTextInput.GetOffsetFromPosition(ActiveTextInput.BeginningOfDocument, ActiveTextInput.SelectedTextRange.start),
ActiveTextInput.GetOffsetFromPosition(ActiveTextInput.SelectedTextRange.start, ActiveTextInput.SelectedTextRange.end)
);
// if selected range is empty, include the character next to the selector in the current range
if (selectionRange.Length.Equals(0))
selectionRange = new NSRange(selectionRange.Location - 1, 1);
return selectionRange;
}
代码在 IF 行引发异常:System.NullReferenceException: Object reference not set to an instance of an object。
这是测试属性存在的正确方法吗?此外,我如何测试我的文本是粗体还是下划线,因为它们是单个属性 (CTStringAttributeKey.Font),我检查了一些示例 (NSAttributedString Color Test),但颜色不同,因为它有自己的属性键。
我想要实现的是一个带有简单标记的富文本编辑器,就像 Word 对 B/U/I/Color 所做的那样。
【问题讨论】:
标签: xamarin.ios xamarin nsattributedstring