2

This answer shows how to enter a string into an NSScrollView in Swift 4 (when developing Mac apps in Xcode 10):

@IBOutlet weak var myScrollView: NSScrollView!
myScrollView.documentView!.insertText("Hello world")

But how do you read this text (get the text string back into a variable)?

So similar to what stringValue does for NSTextField:

@IBOutlet weak var myTextField: NSTextField!
var myTextString = myTextField.stringValue

I'm struggling to find straightforward documentation. Apple's own documentation seems to be shallow at this point, but they are indicating that this is the right component to use:

enter image description here

bjornte
  • 749
  • 1
  • 9
  • 31
  • You can't enter text in a `NSScrollView`, you can enter text in a `NSTextView` (inside a `NSScrollView`). – Willeke Nov 29 '18 at 00:36
  • 1
    Possible duplicate of [Getting formatted string from NSTextView](https://stackoverflow.com/questions/40358955/getting-formatted-string-from-nstextview) – Willeke Nov 29 '18 at 00:36
  • @Willeke I can't get `attributedStringValue`, as indicated in the answer you link to, to work? Both for `NSScrollView` and `NSView`, I get "Value has no member `attributedStringValue`"? Also it says "Value of type `NSScrollView?` has no member `NSTextView`"? – bjornte Nov 29 '18 at 00:44
  • @Willeke, if you look at the first code block above, it works. It sets the text, which I assume is in the `documentView`. So I'm looking for a way to read it. – bjornte Nov 29 '18 at 00:50
  • Use the fast enumeration on myScrollView to read all subViews inside of it. – El Tomato Nov 29 '18 at 01:20
  • Don't use the scroll view, the text is inside the text view (which is the document view and is inside the clipview inside the scroll view). Add an outlet to the text view and use this outlet. – Willeke Nov 29 '18 at 02:53
  • @ElTomato and @Willeke; I can access the NSClipView with a `for…in` statement, but I still don't get how to extract the text. If you have a working example in code it would be great to see :-) – bjornte Nov 29 '18 at 12:36

1 Answers1

2
let myTextView: NSTextView = myScrollView.documentView! as! NSTextView
let myText:String = myTextView.string
bjornte
  • 749
  • 1
  • 9
  • 31