我的目标是创建一个类似于Google文档文本编辑器的视图,并在文本后面添加注释,其中包含注释。 qazxsw poi
我的解决方案是让包含一个NSScrollView
(设置为文档视图),滚动并包含文本的NSView
和其他将成为亮点的NSTextView
s。
要做到这一点,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]))
...
可以这样做吗?
根据您的要求,您可以通过使用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)
}
}