问题
How can I get the selected text's string from a NSTextView
as an NSString
?
Your help is greatly appreciated.
回答1:
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]];
回答2:
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.
来源:https://stackoverflow.com/questions/14024124/get-selection-highlighted-text-string-from-nstextview-objective-c