【问题标题】:Bulleted list with NSTextList in NSTextView example?NSTextView 示例中带有 NSTextList 的项目符号列表?
【发布时间】:2016-07-17 12:54:24
【问题描述】:

我想在 NSTextView 中解析用户输入,以便以“-”开头的行会自动开始一个项目符号列表。我必须对 NSTextView.textStorage 做什么才能启用项目符号列表,以便在每个项目符号行后按 Enter 时自动显示下一个项目符号?

我找到了一些示例,但它们都是手动插入项目符号的,所以我想知道如果您必须自己手动插入框符号,那么指定 let textList = NSTextList(markerFormat: "{box}", options: 0) 有什么意义?

目前我正在尝试在自定义 NSTextView 中实现这一点,并覆盖 shouldChangeTextInRange(affectedCharRange: NSRange, replacementString: String?) 所以一个简单的例子可以解决最简单的“-”输入案例,启动一个自动项目符号列表,将受到高度重视。

更新:

这是我目前正在使用的代码:

override func shouldChangeTextInRange(affectedCharRange: NSRange, replacementString: String?) -> Bool {
   super.shouldChangeTextInRange(affectedCharRange, replacementString: replacementString)

   if string == "-" && replacementString == " " {
      let textList = NSTextList(markerFormat: "{disc}", options: 0)
      let textListParagraphStyle = NSMutableParagraphStyle()
      textListParagraphStyle.textLists = [textList]
      let attributes = [NSParagraphStyleAttributeName: textListParagraphStyle]
      string = "\t\(textList.markerForItemNumber(0))\t"
      textStorage?.addAttributes(attributes, range: NSMakeRange(0, textStorage!.string.length))
      return false
   }
   else if affectedCharRange.location > 0 && replacementString == "\n\n" {
      textStorage?.insertAttributedString(NSAttributedString(string: "\t"), atIndex: affectedCharRange.location)
      return true
   }

   return true
}

我只是想解决用户在 NSTextView 中键入“-”作为第一个字符的最简单情况。这就是上面的代码发生的情况:

开头较大的字体来自我设置的typingAttributes。如您所见,这会在以后自动覆盖。

else if 子句返回 false 并直接插入 \n 将阻止 NSTextView 自动添加新项目符号。在我第一次从那里返回true之后,新的子弹自动添加而不调用这个方法???

【问题讨论】:

  • 你有没有想过如何做到这一点?
  • 无所不知 :o(

标签: swift macos cocoa nstextview


【解决方案1】:

尝试通过替换"- " with \u{2022}来添加使用Unicode字符的项目符号

textView.text = " \u{2022} This is a list item!

【讨论】:

  • 我并不想仅仅插入“•”来代替“-”,这当然看起来像一个列表的开头,但它不会在 textView 中创建一个 NSTextList 和因此它缺少正确识别的列表对象免费提供的所有编辑功能。如果您在第一个项目的末尾按 Enter,则 textView 不会添加以项目符号开头的下一个项目。正确答案需要说明如何正确地将 NSTextList 插入 NSTextView。
猜你喜欢
  • 1970-01-01
  • 2017-09-30
  • 2015-01-01
  • 2012-11-28
  • 2017-10-04
  • 2011-05-11
  • 1970-01-01
  • 2011-07-04
  • 1970-01-01
相关资源
最近更新 更多