我的目标是制作一个类似于 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/