NSView和NSScrollView中的NSTextView

问题描述 投票:7回答:2

我的目标是创建一个类似于Google文档文本编辑器的视图,并在文本后面添加注释,其中包含注释。 qazxsw poi

我的解决方案是让Highlight包含一个NSScrollView(设置为文档视图),滚动并包含文本的NSView和其他将成为亮点的NSTextViews。

要做到这一点,NSView的大小必须像它直接属于NSTextView一样。但是,我不能让NSScrollView有这种行为。

我对布局的代码是:

LatinViewController:的loadView()

NSTextView

拉丁语查看:的init()

...
let latinView = LatinView()
latinView.autoresizingMask = [.ViewWidthSizable]
latinView.wantsLayer = true
latinView.layer?.backgroundColor = Theme.greenColor().CGColor
self.latinView = latinView
scrollView.documentView = latinView
...

LatinTextView:init()

...
let textView = LatinTextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.string = "Long string..."
self.addSubview(textView)
self.textView = textView

self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[text]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["text": textView]))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[text]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["text": textView]))
...

可以这样做吗?

swift cocoa nstextview
2个回答
1
投票

根据您的要求,您可以通过使用NSAttributedString和NSTextView来实现功能。以下是示例代码A NSTextView已经带有丰富的文本编辑功能,格式存储可以通过NSAttributedString实现

...
self.minSize = NSMakeSize(0, 0)
self.maxSize = NSMakeSize(0, CGFloat(FLT_MAX))
self.verticallyResizable = true
self.horizontallyResizable = false
self.textContainer?.heightTracksTextView = false
...

import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet var textView:NSTextView! func applicationDidFinishLaunching(aNotification: NSNotification) { let singleAttribute1 = [ NSForegroundColorAttributeName: NSColor.purpleColor() , NSBackgroundColorAttributeName: NSColor.yellowColor() ] let multipleAttributes = [ NSForegroundColorAttributeName: NSColor.redColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue ] var string1 = NSAttributedString(string: "Hello World", attributes: singleAttribute1) var string2 = NSAttributedString(string: " This is knowstack", attributes: multipleAttributes) var finalString = NSMutableAttributedString(attributedString: string1) finalString.appendAttributedString(string2) self.textView.textStorage?.setAttributedString(finalString) } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } @IBAction func getAttributedString(sender:AnyObject){ var attributedString = self.textView.attributedString() print(attributedString) } }


1
投票

enter image description here(由NSLayoutManager使用,和NSTextView一般使用)具有一个特殊功能,用于在不更改源:临时属性的情况下在屏幕上显示文本之前更改文本。

查找NSAttributedString文档,查找名称中包含“TemporaryAttribute”的方法:

NSLayoutManager

它们应该在拼写检查期间用作例如绿色/红色下划线的单词,或者仅用于暂时突出显示文本的一部分。它们允许您仅为显示目的修改文本部分的外观,而无需修改原始属性文本源。

© www.soinside.com 2019 - 2024. All rights reserved.