如何在 NSTextView 中的一行换行文本中获取等宽字体的字符数?

How to get the number of characters of monospaced font in a line of wrapped text in NSTextView?

我想知道在 NSTextView 中,有多少个字母具有一整行由没有空格和换行符的字母组成的换行文本。文本的字体定义为等宽字体。我找不到如何获取字体的宽度(我认为我可以根据 NSTextView 的宽度和字体的宽度来计算它)。

假设您的文本视图包含整行或多行:

var range = NSMakeRange(NSNotFound, 0)
textView.layoutManager?.lineFragmentRectForGlyphAtIndex(0, effectiveRange: &range)

print(range.length) // number of characters that can be fitted on a single line