jam*_*ick 7 cocoa nstextview swift
我的目标是创建一个类似于Goole Docs文本编辑器的视图,并在文本后面有注释突出显示有注释.

我的解决方案是NSScrollView包含一个NSView(设置为文档视图),滚动并包含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
...
Run Code Online (Sandbox Code Playgroud)
拉丁语查看:的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]))
...
Run Code Online (Sandbox Code Playgroud)
LatinTextView:的init()
...
self.minSize = NSMakeSize(0, 0)
self.maxSize = NSMakeSize(0, CGFloat(FLT_MAX))
self.verticallyResizable = true
self.horizontallyResizable = false
self.textContainer?.heightTracksTextView = false
...
Run Code Online (Sandbox Code Playgroud)
可以这样做吗?
小智 1
从您的要求看来,您只需使用 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)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1208 次 |
| 最近记录: |