NSTextView does word-wrap by default. How can I disable this? I'm making a JSON code viewer, so I have to disable this.
I got solution from: http://lists.apple.com/archives/cocoa-dev/2008/May/msg02396.html
You have to set NSTextView's maximum width to very large number to make this work correctly. (Just copy maximum height) And enable horizontal scrolling of NSScrollView which is superview of the NSTextView. See these pictures:
http://www.flickr.com/photos/47601728@N06/4759470529/
http://www.flickr.com/photos/47601728@N06/4759470533/
I discovered my old sample code was insufficient to make it fully work correctly. (because of SDK version?) Also Here's my full source code snippet which disables word-wrap in OSX 10.8 SDK.
[self setMaxSize:CGSizeMake(FLT_MAX, FLT_MAX)];
[self setHorizontallyResizable:YES];
[[self textContainer] setWidthTracksTextView:NO];
[[self textContainer] setContainerSize:CGSizeMake(FLT_MAX, FLT_MAX)];
Now Apple is providing an official guide to create NSTextView
correctly. I hope this helps.
I posted an example project on Github. See this page for specific implementation: https://github.com/Eonil/CocoaProgrammaticHowtoCollection/blob/master/ComponentUsages/TextView/ExampleApplicationController.swift?ts=4
Here's a code snippet from the sample project.
if wordwrap {
/// Matching width is also important here.
let sz1 = scroll1.contentSize
text1.frame = CGRect(x: 0, y: 0, width: sz1.width, height: 0)
text1.textContainer!.containerSize = CGSize(width: sz1.width, height: CGFloat.max)
text1.textContainer!.widthTracksTextView = true
} else {
text1.textContainer!.widthTracksTextView = false
text1.textContainer!.containerSize = CGSize(width: CGFloat.max, height: CGFloat.max)
}
The three lines given in the accepted answer by Eonil alone did not work for me, the resulting text view did not scroll horizontally and therefore there was no way to see the clipped part of the long lines.
The full code snippet from the referenced cocoa-dev thread did produce the correct results. Specifically, this set of steps:
NSSize layoutSize = [textView maxSize];
layoutSize.width = layoutSize.height;
[textView setMaxSize:layoutSize];
[[textView textContainer] setWidthTracksTextView:NO];
[[textView textContainer] setContainerSize:layoutSize];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With