【问题标题】:monotouch nsattributedstring style/attribute testingmonotouch nsattributedstring 样式/属性测试
【发布时间】: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


    【解决方案1】:

    我猜这个问题是一个基本的 c# 问题,当尝试访问 <Dictionary>.ObjectForKey() 方法时,如果字典中没有设置密钥,则会引发 NullReference 异常,所以在尝试访问之前使用 <Dictionary>.TryGetValue()数据的键名

    【讨论】:

      猜你喜欢
      • 2014-02-20
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 2013-11-15
      • 1970-01-01
      • 2016-04-03
      相关资源
      最近更新 更多