【发布时间】: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