我的目标是制作一个与Goole Docs文本编辑器类似的 View ,并在其中有注释的文本后面突出显示注释。
我的解决方案是让一个NSScrollView
包含一个NSView
(设置为文档 View ),它滚动并包含文本的NSTextView
和其他将突出显示的NSView
。
为此,NSTextView
必须确定大小,就好像它直接属于NSScrollView
一样。但是,我无法使NSTextView
具有此行为。
我的布局代码是:
LatinViewController:loadView()
...
let latinView = LatinView()
latinView.autoresizingMask = [.ViewWidthSizable]
latinView.wantsLayer = true
latinView.layer?.backgroundColor = Theme.greenColor().CGColor
self.latinView = latinView
scrollView.documentView = latinView
...
LatinView: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]))
...
LatinTextView:init()
...
self.minSize = NSMakeSize(0, 0)
self.maxSize = NSMakeSize(0, CGFloat(FLT_MAX))
self.verticallyResizable = true
self.horizontallyResizable = false
self.textContainer?.heightTracksTextView = false
...
能做到吗?
最佳答案
从您的需求看来,您可以简单地通过使用NSAttributedString和NSTextView来实现该功能。以下是示例代码
NSTextView已经具有丰富的文本编辑功能,并且可以通过NSAttributedString实现格式存储
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)
}
}
关于swift - NSView和NSScrollView中的NSTextView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35299204/