简体   繁体   English

从 NSTextView Objective-C 获取选择(突出显示的文本)字符串

[英]Get selection (highlighted text) string from NSTextView Objective-C

How can I get the selected text's string from a NSTextView as an NSString ?如何从NSTextView获取选定文本的字符串作为NSString

Your help is greatly appreciated.非常感谢您的帮助。

An NSText can have more than only one selection.一个 NSText 可以有多个选择。 Check it out with TextEditapp: select a string with the mouse while pressing CMD.使用 TextEditapp 查看:在按下 CMD 的同时用鼠标选择一个字符串。 So you can select as many strings as you want.因此,您可以根据需要选择任意数量的字符串。 Therefore I think, a more common solution is to use:因此我认为,更常见的解决方案是使用:

NSArray *ranges = [myTextView selectedRanges];

and then extract the strings one by one.然后一一提取字符串。

Since NSTextView is a subclass of NSText, you can use NSText instance methods to figure out the selected string like so:由于 NSTextView 是 NSText 的子类,因此您可以使用NSText实例方法来计算所选字符串,如下所示:

NSString *selected = [[myTextView string] 
                      substringWithRange:[myTextView selectedRange]];

Swift 5, handling multiple selections of NSTextView based on @vauxhall's answer Swift 5,根据@vauxhall 的回答处理多个 NSTextView 选择

extension NSTextView {
    var selectedText: String {
        var text = ""
        for case let range as NSRange in self.selectedRanges {
            text.append(string[range]+"\n")
        }
        text = String(text.dropLast())
        return text
    }
}

extension String {
    subscript (_ range: NSRange) -> Self {
        .init(self[index(startIndex, offsetBy: range.lowerBound) ..< index(startIndex, offsetBy: range.upperBound)])
    }
}

Swift迅速

extension NSTextView {
    var selectedText: String {
        string[selectedRange()]
    }
}

extension String {
    subscript (_ range: NSRange) -> Self {
        .init(self[index(startIndex, offsetBy: range.lowerBound) ..< index(startIndex, offsetBy: range.upperBound)])
    }
}

Usage用法

let textView = NSTextView()
print(textView.selectedText)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM