Sam*_*Sam 6 cocoa nslayoutmanager nstextview nstextstorage swift
在苹果文档之后,我试图NSTextView通过它的两个构造函数方法设置一个简单的.
我将以下代码放在viewDidAppear内容视图的视图控制器的方法中.NSTextViewtextView 是一个实例,frameRect是内容视图的框架.
以下Swift代码可以工作(给我一个可编辑的textView,屏幕上显示文字):
textView = NSTextView(frame: frameRect!)
self.view.addSubview(textView)
textView.textStorage?.appendAttributedString(NSAttributedString(string: "Hello"))
Run Code Online (Sandbox Code Playgroud)
以下不起作用(文本视图不可编辑,屏幕上不显示任何文本):
var textStorage = NSTextStorage()
var layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
var textContainer = NSTextContainer(containerSize: frameRect!.size)
layoutManager.addTextContainer(textContainer)
textView = NSTextView(frame: frameRect!, textContainer: textContainer)
textView.editable = true
textView.selectable = true
self.view.addSubview(textView)
textView.textStorage?.appendAttributedString(NSAttributedString(string: "Hello more complex"))
Run Code Online (Sandbox Code Playgroud)
我在第二个例子中做错了什么?我试图遵循Apple的"可可文本架构指南"中给出的示例,他们NSTextView通过显式实例化其辅助对象Web来讨论设置.
您需要保留对NSTextStorage您创建的变量的引用.我不太确定这一切的机制,但看起来文本视图只保留对其文本存储对象的弱引用.一旦此对象超出范围,文本视图就不再可用.我想这符合MVC设计模式,其中视图(NSTextView在本例中)意味着独立于其模型(NSTextStorage对象).
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
var textView: NSTextView!
var textStorage: NSTextStorage! // STORE A REFERENCE
func applicationDidFinishLaunching(aNotification: NSNotification) {
var view = window.contentView as NSView
textStorage = NSTextStorage()
var layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
var textContainer = NSTextContainer(containerSize: view.bounds.size)
layoutManager.addTextContainer(textContainer)
textView = NSTextView(frame: view.bounds, textContainer: textContainer)
textView.editable = true
textView.selectable = true
view.addSubview(textView)
textView.textStorage?.appendAttributedString(NSAttributedString(string: "Hello more complex"))
}
}
Run Code Online (Sandbox Code Playgroud)