在NSScrollView(Swift)中显示文本

ixa*_*any 7 xcode nsscrollview nsmutableattributedstring swift

刚开始学习Swift并创建了一个小macOS应用程序,我想在其中使用a NSScrollView来显示属性String.我试过了:

@IBOutlet var ScrollViewOutlet : NSScrollView
var attributedString = NSMutableAttributedString(string: myText)
ScrollViewOutlet.insertText(attributedString)
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用.我发现有点令人困惑,因为做一个相同的NSTextView工作就像一个魅力.

我在这里错过了什么?

Jac*_*sox 9

在下面的示例中,我在界面构建器中添加了scrollView作为我的起点.

如果您的scrollView/textView为空/空白,或者如果您需要在scrollView/textView中已有的文本前面附加文本,则以下情况有效.如果框中已有文本,则新文本将插入现有文本的前面.

documentView是一个NSTextView

Swift 4.0

@IBOutlet weak var imageDestinationDirectory: NSScrollView!

...

let destinationText = "Text to display"
imageDestinationDirectory.documentView!.insertText(destinationText)
Run Code Online (Sandbox Code Playgroud)


ixa*_*any 6

似乎Xcode的早期测试版(以Swift为特色)在这类插座上存在一些严重的问题(正如你在这里看到的那样:http://swiftwtf.tumblr.com/post/88387419568/nstextview).但是,因为Xcode 6 Beta 6它的工作原理.

textFieldOutlet.textStorage.mutableString.setString("Hello w0rld!")
Run Code Online (Sandbox Code Playgroud)

为了处理字符串,为创造一个出口textField,而不是的scrollView本身也是一个更好的做法.


Ken*_*ses 5

Apple有一篇关于以编程方式在滚动视图中设置文本视图的文章.文本系统用户界面层编程指南:在NSScrollView中放置NSTextView对象您应该阅读它以获得最大的理解,但这里是代码:

NSScrollView *scrollview = [[NSScrollView alloc] initWithFrame:[[theWindow contentView] frame]];
NSSize contentSize = [scrollview contentSize];

[scrollview setBorderType:NSNoBorder];
[scrollview setHasVerticalScroller:YES];
[scrollview setHasHorizontalScroller:NO];
[scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];

theTextView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, contentSize.width, contentSize.height)];
[theTextView setMinSize:NSMakeSize(0.0, contentSize.height)];
[theTextView setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
[theTextView setVerticallyResizable:YES];
[theTextView setHorizontallyResizable:NO];
[theTextView setAutoresizingMask:NSViewWidthSizable];

[[theTextView textContainer] setContainerSize:NSMakeSize(contentSize.width, FLT_MAX)];
[[theTextView textContainer] setWidthTracksTextView:YES];
[scrollview setDocumentView:theTextView];
[theWindow setContentView:scrollview];
[theWindow makeKeyAndOrderFront:nil];
[theWindow makeFirstResponder:theTextView];
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过对其textStorage对象进行操作来设置文本视图的文本:

theTextView.textStorage.attributedString = attributedString;
Run Code Online (Sandbox Code Playgroud)