简体   繁体   中英

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

How can I get the selected text's string from a NSTextView as an NSString ?

Your help is greatly appreciated.

An NSText can have more than only one selection. Check it out with TextEditapp: select a string with the mouse while pressing 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:

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

Swift 5, handling multiple selections of NSTextView based on @vauxhall's answer

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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