如何在文本视图中的某个索引处获取字符的行号和列号?

时间:2015-04-09 20:29:04

标签: macos swift nstextview

我有一个NSTextView我有很多文字。

如何在某个索引处获取字符的行号和列号?

让我们说,我在NSTextView

中有这个文字
"This is just a\ndummy text\nto show you\nwhat I mean."

我需要第16个字符的行号和列号。在这种情况下:

Line: 2
Column: 2

如何使用Swift计算/获取此内容?

另一个例子:

"This is just a\ndummy text\nto show you\nwhat I mean."

我想要 15th (或16,如果\n也被计算在内)的行号和行号,如下所示:

Line: 2
Column: 1

1 个答案:

答案 0 :(得分:4)

你只需要使用String方法componentsSeparatedByString打破你的文本行,然后你只需要保持你的行,列和字符位置的计数如下:

extension String {
    func characterRowAndLineAt(position: Int) -> (character: String, line: Int, column:Int)? {
        var lineNumber = 0
        var characterPosition = 0
        for line in components(separatedBy: .newlines) {
            lineNumber += 1
            var columnNumber = 0
            for column in line {
                characterPosition += 1
                columnNumber += 1
                if characterPosition == position {
                    return (String(column), lineNumber, columnNumber )
                }
            }
            characterPosition += 1
            if characterPosition == position {
                return ("\n", lineNumber, columnNumber+1 )
            }
        }
        return nil
    }
}

let myText    = "This is just a\ndummy text\nto show you\nwhat I mean."
let result    = myText.characterRowAndLineAt(position: 16) // "(.0 "d", .1 2, .2 1)"
let character = result?.character  // "d"
let line      = result?.line       // 2
let column    = result?.column     // 1