OSX Swift:NSTextView上的源文件错误中的编辑器占位符

问题描述:

我不断收到'编辑器占位符在源文件'错误。我试图访问我的NSTextView的文本,但我似乎没有做正确的。OSX Swift:NSTextView上的源文件错误中的编辑器占位符

@IBAction func cancelButton(sender: AnyObject) { 

    dismissViewController(self) 
} 

@IBAction func saveButtonHandler(sender: AnyObject) { 

    let Name: String! = nameField.stringValue; 
    let Time: String! = timeField.stringValue; 
    let Yum: String! = yumField.stringValue; 
    let Instruct = (instructionField.textStorage as NSAttributedString!).string; 
    let recipe = Recipe(name: Name, time: Time, yum: Yum, type: foodType, instructions: Instruct) 

    dismissViewController(self) 
} 

的问题来自于线

let Instruct = (instructionField.textStorage as NSAttributedString!).string; 

我在做什么错?

首先,如果您正在使用故事板或xib,则不能将出口设置为NSTextView。解决方法是为包含NSScrollView的目标文本视图创建一个Outlet。因此,请务必保持引用instructionField本身和它包含滚动视图这样:

@IBOutlet weak var scrollView : NSScrollView! 

var instructionField : NSTextView { 
    get { 
     return scrollView.contentView.documentView as! NSTextView 
    } 
} 

接下来,你不访问包含在与textStorage文本视图中的文本。用于获取包含在instructionField文本的正确执行如下:

instructionField.string 

这是String?类型。现在


,如果你想从instructionFieldNSAttributedString,你可以做到这一点,像这样以避免强行展开可选:

guard let str = instructionField.string else { /* else */ } 
guard let attrStr = str as? NSAttributedString else { /* else */ } 

最后

最后的修正您的问题行可能类似于以下内容:

guard let Instruct = instructionField.string else { /* else */ } 
+0

非常感谢!你的建议很有用,我从中学到了很多。 –

+0

没问题! @WD – Wes