Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text from NSTextView in Swift

Tags:

macos

swift

I have an NSTextView that users will type text into. I am using this instead of an NSTextField because I need it to support adding a new line when the user hits enter (This doesn't seem to work with NSTextField, but it does with NSTextView)

I can't for the life of me figure out how to get all the text out of the NSTextView.

This SO answer tells me how to do it in Objective-C:

How to find the text in an NSTextView?

But I'm having a hard time making the jump to Swift. If I try to cast the textStorage property to NSAttributedString, I get the error "Cannot convert the expression type NSTextStorage? to type NSAttributedString".

This is an OSX application, not an iPhone application, if that makes any difference for some reason.

Thanks in advance for the help.

like image 509
Whatever Man Avatar asked Oct 27 '14 19:10

Whatever Man


2 Answers

I was forgetting the exclamation point when casting. I needed to do this: (the name of the NSTextView is txtPhoneNumbers)

    (txtPhoneNumbers.textStorage as NSAttributedString!).string
like image 166
Whatever Man Avatar answered Nov 16 '22 17:11

Whatever Man


Swift 5

A simple solution to getting the string of an NSTextView.

if let str = textView.textStorage?.string {
    // do something with string
}
like image 2
skymook Avatar answered Nov 16 '22 15:11

skymook