monotouch nsattributedstring样式/属性测试

时间:2013-12-05 16:47:37

标签: xamarin.ios xamarin nsattributedstring

我在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。

1 个答案:

答案 0 :(得分:1)

问题是一个基本的c#问题我想,在尝试访问<Dictionary>.ObjectForKey()方法时,如果未在字典中设置密钥,则抛出NullReference异常,所以只需使用<Dictionary>.TryGetValue()之前试图通过它的keyname访问数据